2010-03-25 73 views
0

是否有帮助我任何与此框架:(想,也许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; 
    } 
} 

回答

0

改为使用抽象类(如果您坚持使用接口,请使用工厂模式)。

对于抽象类,您只需在默认构造函数中进行必要的填充并添加一点反射。

喜欢的东西:

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); 
     } 
    } 
    } 
} 

免责声明:代码可能无法编译,我只是写它从我的头顶。