当具有属性的类被实例化时的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";

最新更新