C# 属性,它只能位于具有另一个属性的类中的方法上
本文关键字:属性 另一个 方法 于具 | 更新日期: 2023-09-27 18:36:28
在 C# 中,是否可以对属性施加限制,使其只能位于具有另一个属性的类中的方法上?
[MyClassAttribute]
class Foo
{
[MyMethodAttribute]
public string Bar()
}
其中"MyMethodAttribute"只能位于具有"MyClassAttribute"的类中。
这可能吗?如果是这样,怎么能做到?
如果要尝试对方法属性进行运行时验证,可以执行以下操作:
public abstract class ValidatableMethodAttribute : Attribute
{
public abstract bool IsValid();
}
public class MyMethodAtt : ValidatableMethodAttribute
{
private readonly Type _type;
public override bool IsValid()
{
// Validate your class attribute type here
return _type == typeof (MyMethodAtt);
}
public MyMethodAtt(Type type)
{
_type = type;
}
}
[MyClassAtt]
public class Mine
{
// This is the downside in my opinion,
// must give compile-time type of containing class here.
[MyMethodAtt(typeof(MyClassAtt))]
public void MethodOne()
{
}
}
然后使用反射查找系统中的所有ValidatableMethodAttributes
,并调用IsValid()
。这不是很可靠,而且相当脆弱,但这种类型的验证可以实现您正在寻找的目标。
或者传递类的类型 ( Mine
),然后在IsValid()
使用反射来查找Mine
类型上的所有属性。
你也许可以使用PostSharp来做到这一点:(参见:本教程中的编译时验证)
然后在您的属性中,将使用类似于以下内容的代码检查父类:
public class MyCustomAttribute : Attribute
{
public MyCustomAttribute()
{
if (GetType().CustomAttributes.Count(attr => attr.AttributeType == typeof (MyCustomClassAttribute)) < 1)
{
throw new Exception("Needs parent attribute") //Insert Postsharp method of raising compile time error here
}
不能对用户定义的属性执行此操作。但我相信编译器有这样的机制,内置FieldOffsetAttribute
使用它。
struct MyStruct
{
[FieldOffset(1)] //compile error, StructLayoutAttribute is required
private int _num;
}
编辑我认为如果你使用PostSharp之类的东西注入构建过程是可行的。