c# 如何通過反射 獲取\設置屬性值、



//定義類
public class MyClass
{
public int Property1 { get; set; }
}
static void Main()
{
MyClass tmp_Class = new MyClass();
tmp_Class.Property1 = 2;
Type type = tmp_Class.GetType(); //獲取類型
System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //獲取指定名稱的屬性
int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //獲取屬性值
Console.WriteLine(value_Old);
propertyInfo.SetValue(tmp_Class, 5, null); //給對應屬性賦值
int value_New = (int)propertyInfo.GetValue(tmp_Class, null);
Console.WriteLine(value_New);

}

 

其它應用請參考:http://www.bitscn.com/pdb/dotnet/200804/138760.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM