C# 访问get访问器内的properties属性

C# 访问get访问器内的properties属性,c#,.net,custom-attributes,C#,.net,Custom Attributes,我正在为我的属性创建一个自定义属性,想知道是否有人知道我如何访问get访问器中的属性值 public class MyClass { [Guid("{2017ECDA-2B1B-45A9-A321-49EA70943F6D}")] public string MyProperty { get { return "value loaded from guid"; } } } 把这种事情的智慧放在一边 public string MyProperty

我正在为我的属性创建一个自定义属性,想知道是否有人知道我如何访问get访问器中的属性值

public class MyClass
{
    [Guid("{2017ECDA-2B1B-45A9-A321-49EA70943F6D}")]
    public string MyProperty
    {
        get { return "value loaded from guid"; }
    }
}

把这种事情的智慧放在一边

public string MyProperty
{
    get
    {
        return this.GetType().GetProperty("MyProperty").GetCustomAttributes(typeof(GuidAttribute), true).OfType<GuidAttribute>().First().Value;
    }
}
公共字符串MyProperty
{
得到
{
返回此.GetType().GetProperty(“MyProperty”).GetCustomAttributes(typeof(GuidAttribute),true).OfType().First()值;
}
}

把这种事情的智慧放在一边

public string MyProperty
{
    get
    {
        return this.GetType().GetProperty("MyProperty").GetCustomAttributes(typeof(GuidAttribute), true).OfType<GuidAttribute>().First().Value;
    }
}
公共字符串MyProperty
{
得到
{
返回此.GetType().GetProperty(“MyProperty”).GetCustomAttributes(typeof(GuidAttribute),true).OfType().First()值;
}
}

您可以通过反射检索属性及其自定义属性,如下所示:

// Get the property
var property = typeof(MyClass).GetProperty("MyProperty");

// Get the attributes of type “GuidAttribute”
var attributes = property.GetCustomAttributes(typeof(GuidAttribute), true);

// If there is an attribute of that type, return its value
if (attributes.Length > 0)
    return ((GuidAttribute) attributes[0]).Value;

// Otherwise, we’re out of luck!
return null;

可以通过反射检索属性及其自定义属性,如下所示:

// Get the property
var property = typeof(MyClass).GetProperty("MyProperty");

// Get the attributes of type “GuidAttribute”
var attributes = property.GetCustomAttributes(typeof(GuidAttribute), true);

// If there is an attribute of that type, return its value
if (attributes.Length > 0)
    return ((GuidAttribute) attributes[0]).Value;

// Otherwise, we’re out of luck!
return null;

为什么不能从属性返回GUID?为什么需要使用自定义属性?@Timwi,我从属性中看到的唯一好处是,您可以在不构造类实例的情况下检查它,但该类的用户也可以从活动实例中获取它,而不必直接使用反射。不确定这是否足以保证复杂性。这是一个简化的示例,返回的值将是从Guid加载的值,而不是返回Guid本身。这仍然不能解释为什么需要自定义属性以及为什么不能将Guid正确地放在代码中。我可以,但是我正在寻找一个可以存储Guid的地方,并且可以从多个地方访问,例如get、set和类的外部。已经将GUID存储在一个常量文件中,但它越来越大,因此我正在寻找一个更易于管理的解决方案。为什么不能从属性返回GUID?为什么需要使用自定义属性?@Timwi,我从属性中看到的唯一好处是,您可以在不构造类实例的情况下检查它,但该类的用户也可以从活动实例中获取它,而不必直接使用反射。不确定这是否足以保证复杂性。这是一个简化的示例,返回的值将是从Guid加载的值,而不是返回Guid本身。这仍然不能解释为什么需要自定义属性以及为什么不能将Guid正确地放在代码中。我可以,但是我正在寻找一个可以存储Guid的地方,并且可以从多个地方访问,例如get、set和类的外部。已经将guid存储在一个常量文件中,但是它变得相当大,所以我正在寻找一个更易于管理的解决方案。