如何解决实例化具有属性的类时的C#回调
当实例化具有特定属性的类Foo
时,是否有类似回调的内容?
有点像下面的伪代码:
void OnObjectWithAttributeInstantiated(Type attributeType,object o) {
// o is the object with the attribute
}
因此,我试图创建属性AutoStore
。想象一下:
给出带有该标签的类Foo
:
[AutoStore]
public class Foo { ... }
然后(无论在何处,在代码的其他地方)都实例化该类
Foo f = new Foo()
我现在想要将此对象f
自动添加到对象列表中(例如,在静态类中)
如果没有这种方法,您是否有一些解决方法的想法?
修改 我不想使用一个超类来这样做,以实现干净的代码
最诚挚的问候
解决方法
我认为您无法做到。因为有属性供您在运行时发现。但是可能的解决方案可能是创建一个工厂来包装整个东西,例如-
public class Factory
{
public static T Instantiate<T>() where T : class
{
// instantiate your type
T instant = Activator.CreateInstance<T>();
// check if the attribute is present
if (typeof(T).GetCustomAttribute(typeof(AutoStore),false) != null)
{
Container.List.Add(instant);
}
return instant;
}
}
public static class Container
{
public static List<object> List { get; set; } = new List<object>();
}
然后您可以像-
一样使用它Foo foo = Factory.Instantiate<Foo>();
foo.Bar = "Some Bar";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。