C# 有没有办法在运行时获取属性的声明方法/属性 OK,考虑下面的场景: public class Foo() { [FooProperty] public int Blah { get { .... } } ... } [AttributeUsage(AttributeTargets.Property)] public class FooPropertyAttribute: Attribute { public FooPropertyAttribute() { //Is there any way to get at runtime a PropertyInfo of the declaring property 'Foo.Blah'? } ... }

C# 有没有办法在运行时获取属性的声明方法/属性 OK,考虑下面的场景: public class Foo() { [FooProperty] public int Blah { get { .... } } ... } [AttributeUsage(AttributeTargets.Property)] public class FooPropertyAttribute: Attribute { public FooPropertyAttribute() { //Is there any way to get at runtime a PropertyInfo of the declaring property 'Foo.Blah'? } ... },c#,reflection,C#,Reflection,我知道这可能不是一个好主意,但最近,在原型化某个类时,出现了一个问题,我很想知道这是否可行。因为你必须积极寻找这些属性,你可以做任何你想做的事情 例如,如果您有这样的代码: foreach (var propertyInfo in type.GetProperties()) { if (propertyInfo.IsDefined(typeof(FooPropertyAttribute), true)) { var attr = (FooPropertyAttri

我知道这可能不是一个好主意,但最近,在原型化某个类时,出现了一个问题,我很想知道这是否可行。

因为你必须积极寻找这些属性,你可以做任何你想做的事情

例如,如果您有这样的代码:

foreach (var propertyInfo in type.GetProperties())
{
    if (propertyInfo.IsDefined(typeof(FooPropertyAttribute), true))
    {
        var attr = (FooPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(FooPropertyAttribute), true)[0];
        attr.FooMethod(propertyInfo); // <-- here
    }
}
foreach(type.GetProperties()中的var propertyInfo)
{
if(propertyInfo.IsDefined(typeof(FooPropertyAttribute),true))
{
var attr=(FooPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(FooPropertyAttribute),true)[0];

属性footMethod(propertyInfo)/?哇,谢谢!我查找了类似的问题,但我没有发现这个问题。谢谢!似乎没有办法使用反射来完成我的要求。在Eugene Podskal提供的链接中,唯一的解决方案似乎是堆栈遍历方法…这不是一个好主意。堆栈遍历方法仅在代码实际运行时有效,并且属性不运行,除非您专门查找它们并在其中运行代码。换句话说,除非您也有我在答案中发布的代码类型,否则将堆栈遍历方法填充到属性构造函数中是不起作用的。如果您必须提供该代码,您也可以像我那样做,在属性上调用一个方法并传入找到它的成员。因此,不,没有办法做您想做的事情,堆栈遍历方法也不会单独工作。理解,感谢提供信息!