[英]Populate properties decorated with an attribute
是否有任何框架可以幫助我:(認為StructureMap可以幫助我)
每當創建“ MyClass”或從IMyInterface繼承的任何其他類的新實例時,我都希望使用[MyPropertyAttribute]裝飾的所有屬性使用該屬性中的Name屬性填充數據庫或某些其他數據存儲中的值。
public class MyClass : IMyInterface
{
[MyPropertyAttribute("foo")]
public string Foo { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class MyPropertyAttribute : System.Attribute
{
public string Name
{
get;
private set;
}
public MyPropertyAttribute(string name)
{
Name = name;
}
}
改用抽象類(如果堅持使用接口,則使用工廠模式)。
使用抽象類,您只需一點點反射就可以在默認構造函數中進行必要的填充。
就像是:
abstract class Base
{
protected Base()
{
var actualtype = GetType();
foreach (var pi in actualtype.GetProperties())
{
foreach (var attr in pi.GetCustomAttributes(
typeof(MyPropertyAttribute), false))
{
var data = GetData(attr.Name); // get data
pi.SetValue(this, data, null);
}
}
}
}
免責聲明:代碼可能無法編譯,我只是從頭開始編寫它。
從codeplex中檢查以下框架: http : //www.codeplex.com/AutoMapper(用於映射)和http://fasterflect.codeplex.com/(用於快速反射)以收集屬性和setvalues或getvalues。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.