簡體   English   中英

在運行時在類上設置屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM