使用C#的属性

C#相对于C++的好处之一是:有属性这个东西,直接能够让你使用,而且得到语法的支持,首先我们来看看C#中如何表示一个属性,例如:

class MyClass

{

     private string myName = string.Empty;

    public MyName

    {

             get{return myName;}

             set{myName = value;}

    }

}

好了,现在我们可以使用如下的方法来访问属性:

  MyClass myClass;

  myClass.MyName ="dddd";

 

这是最普通的方式,另外一种方式就是使用AttributeUsage来定义一个属性类,就象系统里面提供的属性一样。

定义自己的属性类需要从System.Attribute这个类继承,然后使用上面的方法来定义属性,例如:

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]

class MyAttribute:Attribute

{

       public MyAttribute(string name)

       {

              MyName = name;

}

 

private string myName = string.Empty;

public MyName

      {

             get{return myName;}

             set{myName = value;}

      }

}

 

这个属性的使用不同于上面,首先我们需要定义一个类,例如:

[MyAttribute (“MyName is Test”)]

class MyClass

{

}

 

[MyAttribute (“MyName is Test”)]实际上构造一个属性,MyName是指定的内容;但这个属性并不执行,而是在有代码调用MyClassGetTypeGetCustomAttribute的时候才真正的建立代码。

其实这种属性是使用反射机制,为类在运行时保存一些信息,下面是一个使用自定义属性的例子:

using System;

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,

   AllowMultiple=true)]

public class Author : Attribute

{

   public Author(string name)

   {

      this.name = name; version = 1.0;

   }

   public double version;

   string name;

   public string GetName()

   {

      return name;

   }

}

 

[Author("H. Ackerman")]

class FirstClass

{

   /*...*/

}

 

class SecondClass  // 没有定义Author属性

{

   /*...*/

}

 

[Author("H. Ackerman"), Author("M. Knott", version=1.1)]

class Steerage

{

   /*...*/

}

 

class AuthorInfo

{

   public static void Main()

   {

      PrintAuthorInfo(typeof(FirstClass));

      PrintAuthorInfo(typeof(SecondClass));

      PrintAuthorInfo(typeof(Steerage));

   }

   public static void PrintAuthorInfo(Type t)

   {

      Console.WriteLine("Author information for {0}", t);

      Attribute[] attrs = Attribute.GetCustomAttributes(t);

      foreach(Attribute attr in attrs)

      {

         if (attr is Author)

         {

            Author a = (Author)attr;

            Console.WriteLine("   {0}, version {1:f}",

a.GetName(), a.version);

         }

      }

   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值