public class UserDetails
{
public string UserID { get; set; }
public string UserName { get; set; }
}
這裏我想動態添加屬性。 類型和屬性名稱將動態更改,與我想要創建屬性的值。有什麼辦法在c#中動態創建屬性?
public class UserDetails
{
public string UserID { get; set; }
public string UserName { get; set; }
}
這裏我想動態添加屬性。 類型和屬性名稱將動態更改,與我想要創建屬性的值。有什麼辦法在c#中動態創建屬性?
是的,但它很複雜。 檢查執行ICustomTypeDescriptor
。如果你讓你的基類實現它,你將能夠動態地添加屬性。網上有教程,搜索網絡上的界面。第二件事可以使用ExpandoObject。
這樣你就不能從基類繼承,但實現起來要簡單得多。
看起來你可能真的需要的是一個「Property Bag」,即一個無序的容器,你可以在其中插入名稱/值對,其中名稱是一個字符串,值是任何類型的對象。
PropertyBag在網上有很多實現可用;這裏是一個快速而骯髒的例子:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
namespace Demo
{
public static class Program
{
private static void Main(string[] args)
{
var properties = new PropertyBag();
properties["Colour"] = Color.Red;
properties["π"] = Math.PI;
properties["UserId"] = "My User ID";
properties["UserName"] = "Matthew";
// Enumerate all properties.
foreach (var property in properties)
{
Console.WriteLine(property.Key + " = " + property.Value);
}
// Check if property exists:
if (properties["UserName"] != null)
{
Console.WriteLine("[UserName] exists.");
}
// Get a property:
double π = (double)properties["π"];
Console.WriteLine("Pi = " + π);
}
}
public sealed class PropertyBag: IEnumerable<KeyValuePair<string, object>>
{
public object this[string propertyName]
{
get
{
if (propertyName == null)
{
throw new ArgumentNullException("propertyName");
}
if (_dict.ContainsKey(propertyName))
{
return _dict[propertyName];
}
else
{
return null;
}
}
set
{
if (propertyName == null)
{
throw new ArgumentNullException("propertyName");
}
_dict[propertyName] = value;
}
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _dict.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private readonly Dictionary<string, object> _dict = new Dictionary<string, object>();
}
}
這似乎工作,但需要轉換到「靈活」的屬性。
的UserDetails
類
public class UserDetails
{
private dynamic _internal;
public static implicit operator System.Dynamic.ExpandoObject(UserDetails details)
{
return details._internal;
}
public UserDetails()
{
_internal = new System.Dynamic.ExpandoObject();
}
public string UserID
{
get
{
return _internal.UserID;
}
set
{
_internal.UserID = value;
}
}
public string UserName
{
get
{
return _internal.UserName;
}
set
{
_internal.UserName = value;
}
}
}
而使用類
UserDetails user = new UserDetails();
user.UserName = "bill";
user.UserID = "1";
dynamic dynamicUser = (System.Dynamic.ExpandoObject)user;
dynamicUser.newMember = "check this out!";
Console.WriteLine(user.UserName);
Console.WriteLine(user.UserID);
Console.WriteLine(dynamicUser.UserName);
Console.WriteLine(dynamicUser.UserID);
Console.WriteLine(dynamicUser.newMember);
退房動態:http://msdn.microsoft.com/en-us/library/dd264736.aspx – Bort
又如何你將在以後使用該財產?不知道它的類型和名稱.. –
是的,看看這裏: http://stackoverflow.com/questions/6196022/adding-properties-dynamically-to-a-class – Artless