gpt4 book ai didi

只能在具有另一个属性的类中的方法上的 C# 属性

转载 作者:行者123 更新时间:2023-11-30 23:29:09 25 4
gpt4 key购买 nike

在 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类型的所有属性.

关于只能在具有另一个属性的类中的方法上的 C# 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35642147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com