填充用属性修饰的属性
是否有任何框架可以帮助我完成此操作:(认为也许 StructureMap 可以帮助我)
每当我创建“MyClass”的新实例或继承自 IMyInterface 的任何其他类时,我希望用 [MyPropertyAttribute] 装饰的所有属性都填充为使用属性中的属性名称从数据库或其他数据存储中获取值。
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;
}
}
Are there any frameworks that assist me with this: (thinking that perhaps StructureMap can help me)
Whenever I create a new instance of "MyClass" or any other class that inherits from IMyInterface I want all properties decorated with [MyPropertyAttribute] to be populated with values from a database or some other data storage using the property Name in the attribute.
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请改用抽象类(如果您坚持使用接口,则使用工厂模式)。
使用抽象类,您可以通过一些反射在默认构造函数中进行必要的填充。
类似于:
免责声明:代码可能无法编译,我只是从头开始写的。
Use an abstract class instead (or a factory pattern if you insist on an interface).
With an abstract class, you can just do the necessary population in the default constructor with a little bit of reflection.
Something like:
Disclaimer: Code may not compile, I just wrote it from the top of my head.
从 codeplex 检查以下框架:
http://www.codeplex.com/AutoMapper 用于映射和
http://fasterflect.codeplex.com/ 用于快速反射来收集属性和设置值或获取值。
Check the following frameworks from codeplex:
http://www.codeplex.com/AutoMapper for mapping and
http://fasterflect.codeplex.com/ for fast reflection to gather your properties and setvalues or getvalues.