在属性中访问类和属性名

本文关键字:属性 访问 | 更新日期: 2023-09-27 18:03:48

是否有任何方法可以访问您在属性内部附加属性的类和属性名称?

例如

public class User {
    public string Email { get; set; }
    public string FirstName { get; set; }
    [MyAttribute]
    public string LastName { get; set; }
}

然后在MyAttribute类

public class MyAttributeAttribute {
    public MyAttributeAttribute () : base() {
        string className = /*GET CLASS NAME - should return "User" */
        string propertyName = /*GET PROPERTY NAME - should return LastName*/
    }
}

我知道我可以在构造函数中传递信息,但希望有一种简单的方法可以通过反射或…来节省一遍又一遍地重复输入信息

在属性中访问类和属性名

对不起,这是不可能的。也可以是

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; }
}

属性可以在任何地方创建。甚至下面的方法也是创建实例的有效方法:

var att = new MyAttribute();

你的问题可以归结为"我能检测到我的定制类是从哪里实例化的吗?"在我的最后一个例子中,可以使用StackTrace。但是对于属性,它们是由。net运行时构造的,所以你不能走那条路。