如何判断使用接口的实例变量是否应用了自定义属性?
How can I tell if an instance variable using an interface has a custom attribute applied?
我希望能够检查 class 的实例上是否存在自定义属性,但我希望能够从 class 的实例中执行该检查构造函数。看看这个伪代码:
namespace TestPackage
{
public class MyAttribute : Attribute { }
public interface IMyThing { }
public class MyThing : IMyThing
{
private bool HasMyAttribute { get; set; }
public MyThing()
{
if (/* some check for custom attribute */)
{
HasMyAttribute = true;
}
}
}
public class MyWrapper
{
[MyAttribute]
private readonly IMyThing _myThing;
public MyWrapper()
{
_myThing = new MyThing();
}
}
}
我要填写的代码注释所在的 if 语句。这可能吗?
使用这个构造函数:
public MyThing
{
HasMyAttribute =false;
foreach (MemberInfo item in this.GetType().GetCustomAttributes(false))
{
if(item.Name=="MyAttribute")
HasMyAttribute =true;
}
}
属性是在代码中静态定义的,因此是静态的,它们不绑定到实例。它们应用于一个类型或该类型的成员。
在您的情况下,您可以让包装器实现 IMyThing
并使用它代替原始类型,然后将属性应用于 class.
[MyAttribute]
public class MyWrapper : IMyThing
{
private readonly IMyThing _myThing;
public MyWrapper()
{
_myThing = new MyThing();
}
public void DoMyThingStuff()
{
_myThing.DoMyThingStuff();
}
}
然后您可以像这样检查属性:
bool CheckAttribute(IMyThing myThing)
{
Type t = myThing.GetType();
return t.GetCustomAttributes(typeof(MyAttribute), false).Length > 0;
}
如果传递了原始class的一个对象,你得到false
。如果传递了一个包装对象,你会得到 true
.
您还可以从原始 class 派生出 class 而不是创建包装器。
[MyAttribute]
public class MyDerived : MyThing
{
}
我希望能够检查 class 的实例上是否存在自定义属性,但我希望能够从 class 的实例中执行该检查构造函数。看看这个伪代码:
namespace TestPackage
{
public class MyAttribute : Attribute { }
public interface IMyThing { }
public class MyThing : IMyThing
{
private bool HasMyAttribute { get; set; }
public MyThing()
{
if (/* some check for custom attribute */)
{
HasMyAttribute = true;
}
}
}
public class MyWrapper
{
[MyAttribute]
private readonly IMyThing _myThing;
public MyWrapper()
{
_myThing = new MyThing();
}
}
}
我要填写的代码注释所在的 if 语句。这可能吗?
使用这个构造函数:
public MyThing
{
HasMyAttribute =false;
foreach (MemberInfo item in this.GetType().GetCustomAttributes(false))
{
if(item.Name=="MyAttribute")
HasMyAttribute =true;
}
}
属性是在代码中静态定义的,因此是静态的,它们不绑定到实例。它们应用于一个类型或该类型的成员。
在您的情况下,您可以让包装器实现 IMyThing
并使用它代替原始类型,然后将属性应用于 class.
[MyAttribute]
public class MyWrapper : IMyThing
{
private readonly IMyThing _myThing;
public MyWrapper()
{
_myThing = new MyThing();
}
public void DoMyThingStuff()
{
_myThing.DoMyThingStuff();
}
}
然后您可以像这样检查属性:
bool CheckAttribute(IMyThing myThing)
{
Type t = myThing.GetType();
return t.GetCustomAttributes(typeof(MyAttribute), false).Length > 0;
}
如果传递了原始class的一个对象,你得到false
。如果传递了一个包装对象,你会得到 true
.
您还可以从原始 class 派生出 class 而不是创建包装器。
[MyAttribute]
public class MyDerived : MyThing
{
}