C#的属性Attribute的作用

这篇文章主要介绍“C#的属性Attribute的作用”,在日常操作中,相信很多人在C#的属性Attribute的作用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C#的属性Attribute的作用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

柯城网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、自适应网站建设等网站项目制作,到程序开发,运营维护。创新互联成立于2013年到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联

一、属性

属性Attributes在C#中很常用,但事实上很多人对这个东西又很陌生。

从概念上讲,属性提供的是将元数据关系到元素的一种方式。

属性使用的样子,应该都见过:

[Flags] //Attribute public enum DayOfWeek {     Sunday = 1,     Monday = 2,     Tuesday = 4,     Wednesday = 8,     Thursday = 16,     Friday = 32,     Saturday = 64 }

代码中,Flags就是一个属性。

通常,属性会放在类、字段、方法等定义的上面,用来指定特定的内容。

.Net Framework框架提供了一些属性。像常见的Serializable,用来告诉编译器当前的类可以序列化成JSON或XML:

[Serializable] public class SerializableClass { /*...*/ }

需要注意的是,属性在编译时会嵌入到程序集中。这样,我们可以使用反射来获得相应的属性值。

二、自定义属性

自定义属性用处很大,算是我自己比较常用的一个技术。

自定义属性需要从System.Attribute抽象类来继承。

想象一个场景。我们在构建一个手机类。我们需要一个属性来表示手机一些信息,比方口牌和生产年份:

public class MobileInformationAttribute : Attribute {     public string brand { get; set; }     public int yearOfProduct { get; set; }      public MobileInformationAttribute(string Brand, int YearOfProduct)     {         brand = Brand;         yearOfProduct = YearOfProduct;     } }

我们会注意到:属性是一个类,和其它类一样,拥有字段、方法、构造函数和其它成员。

三、使用属性

前面说了,属性可以放在类、字段、方法等定义的上面。

我们来看看上面这个自定义属性的使用:

[MobileInformation("Apple", 2021)] public class IPhone12 { /*...*/ }

这儿需要注意一下:对于自定义属性的名字,如果我们采用xxx+Attribute的名称,则使用时我们可以用短名称xxx。否则,就需要使用完整的名称:

public class abc : Attribute { /*...*/ }  [abc("Apple", 2021)] public class IPhone12 { /*...*/ }

四、限制属性

属性本身也是一个类。所以属性也可以用属性来指定和修饰。

在修饰属性的属性中,有一个框架中的属性用的很多,就是AttributeUsage。这个属性用来限制自定义属性可以修饰的元素类型:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class MobileInformationAttribute : Attribute { /*...*/ }

AttributeTargets是一个枚举,有很多选项,包括类、接口、方法、构造函数、枚举、程序集等。

上边的代码,我们限定了属性只用于指定和修饰类和接口。所以,如果用这个属性来修饰一个字段,编译器会报错。

AttributeUsage还允许我们定义从修饰对象继承的对象,是否也获得属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = true)] public class MobileInformationAttribute : Attribute { /*...*/ }

以及该属性是否可以在一个元素上有多个实例:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public class MobileInformationAttribute : Attribute { /*...*/ }

五、访问属性

有了属性,怎么访问呢?

框架提供了一个方法Attribute.GetCustomAttribute():

var mobileType = typeof(IPhone12); var attributeType = typeof(MobileInformationAttribute); var attribute = (MobileInformationAttribute)Attribute.GetCustomAttribute(mobileType, attributeType); Console.WriteLine($"Mobile is {attribute.brand} {attribute.yearOfProduct}");

六、反射访问

反射最主要的作用,是用来收集对象的数据,而不是对象本身的数据。这些数据包括对象的类型,以及关于对象成员(包括方法、属性、构造函数)的信息,和关于特定程序集的信息。此外,还包括存储在元素属性中的任何信息。

最简单的反射,就是GetType()方法。

int myInt = 5; Type type = myInt.GetType(); Console.WriteLine(type);

除此之外,我们还可以使用反射来获取关于包含给定类型的程序集的信息:

Assembly assembly = typeof(DateTime).Assembly; Console.WriteLine(assembly);  Assembly mobileAssembly = typeof(IPhone12).Assembly; Console.WriteLine(mobileAssembly);

关于反射的内容,不展开讨论。

这儿说的,是通过反射获取类中方法的信息:

public class ReflectedClass {     public string Property1 { get; set; }      public int Add(int first, int second)     {         return first + second;     } }  ReflectedClass reflected = new ReflectedClass(); MemberInfo member = reflected.GetType().GetMethod("Add"); Console.WriteLine(member); //Int32 Add(Int32, Int32)

同样,还可能通过反射获得关于已定义的属性的信息,以及关于对象的构造函数的信息:

PropertyInfo property = reflected.GetType().GetProperty("Property1"); Console.WriteLine(property); //System.String Property1  ConstructorInfo constructor = reflected.GetType().GetConstructor(new Type[0]); Console.WriteLine(constructor); //Void .ctor()

七、使用反射创建实例

这个需要用到system.Activator。这是一个非常强大的类,可以从类型创建对象的实例。

来看看这个方法的使用:

ReflectedClass newReflected = new ReflectedClass();  var reflectedType = newReflected.GetType();  object newObject = Activator.CreateInstance(reflectedType); Console.WriteLine(newObject);

八、使用反射处理泛型

使用反射处理泛型会比处理普通类型麻烦一点。

这里需要知道,Type类上有一个属性用来标识类型是不是泛型:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7 }; Console.WriteLine(numbers.GetType().IsGenericType);

同样,我们也可以用反射来创建一个泛型的实例:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7 };  Type d = numbers.GetType().GetGenericTypeDefinition();  Type[] typeArgs = new Type[] { typeof(int) };  Type constructed = d.MakeGenericType(typeArgs);  object list = Activator.CreateInstance(constructed);  Console.WriteLine(list.GetType());

有一点复杂,但可以实现。

到此,关于“C#的属性Attribute的作用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!

当前题目:C#的属性Attribute的作用
分享链接:https://www.cdcxhl.com/article32/jddgpc.html

成都网站建设公司_创新互联,为您提供软件开发网站排名虚拟主机网站设计Google微信公众号

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设