【问题标题】:C# callback for when a class with attribute got instantiated实例化具有属性的类时的 C# 回调
【发布时间】:2020-10-18 17:05:48
【问题描述】:

当具有特定属性的类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 将被自动添加到对象列表中(例如,在静态类或其他东西中)

如果没有这样的方法,您是否有一些想法如何解决?

编辑 我不想使用一个超类来实现干净的代码

最好的问候 Briskled

【问题讨论】:

  • 我认为这是不可能的。属性被烘焙到编译的代码中,因此知道对象具有属性的唯一方法是查询对象的属性。这就是postsharp.net 所做的事情。

标签: c# class callback attributes initialization


【解决方案1】:

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

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

【讨论】:

  • 谢谢!有点遗憾,这是不可能的,但事实就是如此。也感谢你的想法。我会记住这一点
猜你喜欢
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2011-12-15
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
相关资源
最近更新 更多