.net 如何使用反射获取静态属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/451453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 11:01:06  来源:igfitidea点击:

How to get a Static property with Reflection

.netreflectionstatic

提问by Corey Downie

So this seems pretty basic but I can't get it to work. I have an Object, and I am using reflection to get to it's public properties. One of these properties is static and I'm having no luck getting to it.

所以这看起来很基本,但我无法让它工作。我有一个对象,我正在使用反射来获取它的公共属性。这些属性之一是静态的,我没有运气得到它。

Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
    Return obj.GetType.GetProperty(propName)

End Function

The above code works fine for Public Instance properties, which up until now is all that I have needed. Supposedly I can use BindingFlags to request other types of properties (private, static), but I can't seem to find the right combination.

上面的代码适用于公共实例属性,到目前为止,这是我所需要的。据说我可以使用 BindingFlags 来请求其他类型的属性(私有、静态),但我似乎找不到正确的组合。

Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
    Return obj.GetType.GetProperty(propName, Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public)

End Function

But still, requesting any Static members return nothing. .NET reflector can see the static properties just fine, so clearly I am missing something here.

但是,请求任何静态成员都不会返回任何内容。.NET 反射器可以很好地看到静态属性,所以很明显我在这里遗漏了一些东西。

采纳答案by Corey Downie

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

好的,所以我的关键是使用 .FlattenHierarchy BindingFlag。我真的不知道为什么我只是凭直觉添加它并开始工作。因此,允许我获取公共实例或静态属性的最终解决方案是:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)

回答by Ernest

Or just look at this...

或者看看这个...

Type type = typeof(MyClass); // MyClass is static class with static properties
foreach (var p in type.GetProperties())
{
   var v = p.GetValue(null, null); // static classes cannot be instanced, so use null...
}

回答by earlNameless

This is C#, but should give you the idea:

这是 C#,但应该给你一个想法:

public static void Main() {
    typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static);
}

private static int GetMe {
    get { return 0; }
}

(you need to OR NonPublic and Static only)

(您只需要 OR NonPublic 和 Static)

回答by George

A little clarity...

有点清晰...

// Get a PropertyInfo of specific property type(T).GetProperty(....)
PropertyInfo propertyInfo;
propertyInfo = typeof(TypeWithTheStaticProperty)
    .GetProperty("NameOfStaticProperty", BindingFlags.Public | BindingFlags.Static); 

// Use the PropertyInfo to retrieve the value from the type by not passing in an instance
object value = propertyInfo.GetValue(null, null);

// Cast the value to the desired type
ExpectedType typedValue = (ExpectedType) value;

回答by Igor

myType.GetProperties(BindingFlags.Public | BindingFlags.Static |  BindingFlags.FlattenHierarchy);

This will return all static properties in static base class or a particular type and probably the child as well.

这将返回静态基类或特定类型中的所有静态属性,也可能返回子类。

回答by Andras Zoltan

Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo- where BindingFlagsis not available reliably (depending on target framework).

只是想为自己澄清这一点,同时使用基于的新反射 API TypeInfo- whereBindingFlags不可靠(取决于目标框架)。

In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

在“新”反射中,要获取类型(不包括基类)的静态属性,您必须执行以下操作:

IEnumerable<PropertyInfo> props = 
  type.GetTypeInfo().DeclaredProperties.Where(p => 
    (p.GetMethod != null && p.GetMethod.IsStatic) ||
    (p.SetMethod != null && p.SetMethod.IsStatic));

Caters for both read-only or write-only properties (despite write-only being a terrible idea).

适用于只读或只写属性(尽管只写是一个糟糕的主意)。

The DeclaredPropertiesmember, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

DeclaredProperties成员也不区分具有公共/私有访问器的属性 - 因此要过滤可见性,您需要根据需要使用的访问器进行过滤。例如 - 假设上面的调用已经返回,你可以这样做:

var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);

There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfoquery methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

有一些快捷方法可用 - 但最终我们都会TypeInfo在未来围绕查询方法/属性编写更多扩展方法。此外,新的 API 迫使我们从现在开始考虑我们认为的“私有”或“公共”属性——因为我们必须根据个人访问者过滤自己。

回答by Vyas Bharghava

The below seems to work for me.

以下似乎对我有用。

using System;
using System.Reflection;

public class ReflectStatic
{
    private static int SomeNumber {get; set;}
    public static object SomeReference {get; set;}
    static ReflectStatic()
    {
        SomeReference = new object();
        Console.WriteLine(SomeReference.GetHashCode());
    }
}

public class Program
{
    public static void Main()
    {
        var rs = new ReflectStatic();
        var pi = rs.GetType().GetProperty("SomeReference",  BindingFlags.Static | BindingFlags.Public);
        if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
        Console.WriteLine(pi.GetValue(rs, null).GetHashCode());


    }
}

回答by Ken Henderson

Try this C# Reflectionlink.

试试这个C# 反射链接。

Note I think that BindingFlags.Instance and BindingFlags.Staticare exclusive.

请注意,我认为BindingFlags.Instance 和 BindingFlags.Static是互斥的。