实例化具有属性的 class 时的 C# 回调

C# callback for when a class with attribute got instantiated

当具有特定属性的 class Foo 被实例化时,是否有类似回调的东西? 有点像这个伪代码:

void OnObjectWithAttributeInstantiated(Type attributeType, object o) {
    // o is the object with the attribute
}

所以我试图创建一个属性 AutoStore。想象一下:

给定一个带有该标签的 class Foo

[AutoStore]
public class Foo { ... }

然后(在代码的其他地方,无论在哪里)实例化 class

Foo f = new Foo()

我现在想要这个对象 f 将自动添加到对象列表中(例如,在静态 class 或其他东西中)

如果没有这种方法,您是否有一些解决方法?

编辑 我不想使用 superclass 这样做是为了干净的代码

问候 Briskled

我认为你做不到。因为属性供您在运行时发现。但是一个可能的解决方案可能是创建一个工厂来包装整个东西,比如 -

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";