这是一个关于我如何避免标记界面的例子。
public class AssignableAttribute : Attribute { }
[Assignable]
public class Foo
{
...
}
[Assignable]
public class Bar
{
...
}
我正在尝试将它添加到字典中为什么我不能编写这样的字典以及如何修复它?
Dictionary<string, AssignableAttribute> dictionary = new ...();
dictionary.Add("foo", new Foo());
dictionary.Add("bar", new Bar());
Avoid using marker interfaces (interfaces with no members).
Custom attributes provide a way to mark a type. For more information about custom attributes, see Writing Custom Attributes. Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.
请您参考如下方法:
Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.
这是关键。当您尝试使用这样的泛型时,您正在使用编译时检查。您可以使用 Dictionary<string, Object> 延迟运行时检查,但我认为如果没有某些特殊情况,任何人都不会喜欢这样做 - 这是额外的努力和潜在的错误而没有任何实际好处。
请记住,准则只是建议,并非必须遵守。这个特定的指南甚至会告诉您在什么情况下您不应该遵循它,也就是您目前所处的情况。
