[英]Setting properties on a class at runtime
我正在嘗試在C#中實現以下目標:
public class GenericModel
{
public SetPropertiesFromDataRow(DataColumnCollection columns, DataRow row)
{
foreach(DataColumn column in columns)
{
this.SetProperty(column.ColumnName, row[column.ColumnName]);
}
}
}
DataTable students = ReadStudentsFromDatabase(); // This reads all the students from the database and returns a DataTable
var firstStudent = new GenericModel();
firstStudent.SetPropertiesFromDataRow(students.Columns, students.Rows[0]);
這可以用C#進行嗎(因為它是靜態語言)?
(請注意,此示例是某種偽代碼。)
這是使用ExpandoObject的示例
dynamic eo = new ExpandoObject();
var dic = eo as IDictionary<string, object>;
foreach (string propertyName in XXX)
{
dic[propertyName] = propertyValue;
}
絕對有可能。 C#具有反射系統,使您可以在運行時檢查類結構並設置類元素。 例如,要設置一個屬性this
時候你已經是一個名稱string
可以如下進行:
foreach(DataColumn column in columns) {
PropertyInfo prop = GetType().GetProperty(column.Name);
prop.SetValue(this, row[column.Name]);
}
這假設了幾件事:
DataColumn
對象的名稱與您的類中的屬性的名稱完全匹配,包括大小寫 DataColumn
,即,如果有Xyz
列,則類中必須有一個屬性Xyz
如果這些要求中的任何一個被破壞,將存在運行時錯誤。 您可以用代碼解決它們。 例如,如果希望在通用模型可能缺少某些屬性的情況下使它工作,請在prop
變量上添加null
檢查,並在看到prop ==null
時跳過對SetValue
的調用。
您可以使用反射來做到這一點,例如
objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)
使用動態變量設置動態屬性,如下所示:
class Program{
static void Main(string[] args)
{
dynamic x = new GenericModel();
x.First = "Robert";
x.Last = " Pasta";
Console.Write(x.First + x.Last);
}
}
class GenericModel : DynamicObject
{
Dictionary<string, object> _collection = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _collection.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_collection.Add(binder.Name, value);
return true;
}
}
請參考鏈接: MSDN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.