古詩詞大全網 - 成語用法 - C#特性可以動態修改嗎

C#特性可以動態修改嗎

不能

public class AppSetings

{

class A {

[Display(Name = "name")]

public int M { set; get; }

}

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Hello World!");

Program p = new Program();

p.mian();

Console.ReadLine();

}

public void mian() {

//fun();

A a = new A();

texingSet(a);

texingGet(a);

}

public void texingSet(A a) {

Type type = a.GetType();

PropertyInfo property = type.GetProperty("M");

object[] attributes = property.GetCustomAttributes(true);

DisplayAttribute display = (DisplayAttribute)attributes[0];

DisplayAttribute display2 = (DisplayAttribute)attributes[0];

Type despType = typeof(DisplayAttribute);

PropertyInfo namPropertyInfo = despType.GetProperty("Name");

namPropertyInfo.SetValue(display, "dddd");

Console.WriteLine("-----------------------");

Console.WriteLine("name1:" + display.Name);

Console.WriteLine("name2:" + display2.Name);

Console.WriteLine("-----------------------");

namPropertyInfo.SetValue(display2, "dddd2");

Console.WriteLine("name1:" + display.Name);

Console.WriteLine("name2:" + display2.Name);

Console.WriteLine("-----------------------");

PropertyInfo property2 = type.GetProperty("M");

object[] attributes2 = property2.GetCustomAttributes(true);

DisplayAttribute display3 = (DisplayAttribute)attributes2[0];

Type despType3 = typeof(DisplayAttribute);

PropertyInfo namPropertyInfo2 = despType3.GetProperty("Name");

namPropertyInfo2.SetValue(display2, "dddd3");

Console.WriteLine("name1:" + display.Name);

Console.WriteLine("name2:" + display2.Name);

Console.WriteLine("name3:" + display3.Name);

}

public void texingGet(A a) {

Type type = a.GetType();

PropertyInfo property = type.GetProperty("M");

object[] attributes = property.GetCustomAttributes(true);

DisplayAttribute display = (DisplayAttribute)attributes[0];

Console.WriteLine("name:" + display.Name);

}

}