【发布时间】: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