【发布时间】:2021-03-02 06:55:22
【问题描述】:
我在 C# 中创建了一个自定义属性:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class ExampleAttribute : Attribute
{
}
我希望这仅适用于属性,但更具体地说,适用于不是类(只是基类型)的属性。
例子:
public class ExamplePoco
{
// These should be fine...
[Example]
public string Prop1 { get; set; }
[Example]
public bool Prop2 { get; set; }
[Example]
public int Prop3 { get; set; }
// But this shouldn't be allowed because it's a class, rather than base type
[Example]
public OtherExample Prop4 { get; set; }
}
public class OtherExample
{
public string Other1 { get; set; }
}
有谁知道我会如何在编译时进一步限制这个自定义属性?如果这只能在运行时完成,那么最好的方法是什么?
提前致谢!
【问题讨论】:
-
编译时无法阻止这种情况发生
-
在运行时你会如何处理这个问题?
标签: c# properties attributes custom-attributes