Pet*_*ter 7 c# reflection custom-attributes
有没有办法访问属性中附加属性的类和属性名称?
例如
public class User {
public string Email { get; set; }
public string FirstName { get; set; }
[MyAttribute]
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后在MyAttribute类中
public class MyAttributeAttribute {
public MyAttributeAttribute () : base() {
string className = /*GET CLASS NAME - should return "User" */
string propertyName = /*GET PROPERTY NAME - should return LastName*/
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以在构造函数中传递信息,但是希望有一种简单的方法可以通过反射或者反复来节省一遍又一遍的重新输入信息.
对不起,但不,这是不可能的.你也可以
public class User {
public string Email { get; set; }
public string FirstName { get; set; }
[MyAttrubute]
public string LastName { get; set; }
}
[MyAttrubute]
public class OtherClass {
[MyAttrubute]
public string AnotherProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
可以从任何地方创建属性.即使以下是创建实例的有效方法:
var att = new MyAttribute();
Run Code Online (Sandbox Code Playgroud)
您的问题可归结为"我可以检测自定义类的实例化位置吗?".在我的上一个例子中,可能会使用StackTrace.但是由于属性是由.NET运行时构造的,因此您将无法使用该路由.