【问题标题】:GetValue from list of GetProperties without an instantiated object using reflection使用反射从没有实例化对象的 GetProperties 列表中获取值
【发布时间】:2012-07-31 21:15:24
【问题描述】:
public class SomeClass
{
    public IBy Some1{ get { return By.CssSelector("span[id$=spanEarth]"); } }

    public IBy Some2 { get { return By.CssSelector("span[id$=spanWorm]"); } }

    public IBy Some3 { get { return By.CssSelector("span[id$=spanJim]"); } }
}

是类,我以这种方式使用反射:

var gridRow = Type.GetType(typeof(SomeOtherClassInSameNamespace).AssemblyQualifiedName.Replace("SomeOtherClassInSameNamespace", "SomeClass"), true, true);

var rowList = gridRow.GetProperties().Where(p => p.PropertyType.Name.Contains("IBy")).ToList();

int i = 0;
foreach (var property in rowList)
{
    string test = property.GetValue(gridRow, null).ToString();
}

这会为 objectType 异常提供运行时错误。如何使用反射从属性列表中获取值?

【问题讨论】:

    标签: c# reflection getproperties


    【解决方案1】:

    gridRow 是对Type 对象的引用。 GetValue 的第一个参数是目标对象 - 所以这就像你试图访问 Type 对象上的 SomeClass 属性一样。这显然行不通。

    虽然有hacky ways 在没有引用实例的情况下评估实例属性 - 只要该属性不使用 this - 它们真的很讨厌。

    如果一个属性不需要对象中的任何状态,则改为将其设为静态属性。此时你可以使用null作为目标,就可以了:

    public class SomeClass
    {
        public static IBy Some1 { get { return By.CssSelector("span[id$=spanEarth]"); } }
    
        public static IBy Some2 { get { return By.CssSelector("span[id$=spanWorm]"); } }
    
        public static IBy Some3 { get { return By.CssSelector("span[id$=spanJim]"); } }
    }
    ...
    
    var gridRow = Type.GetType(typeof(SomeOtherClassInSameNamespace)
                                  .AssemblyQualifiedName
                                  .Replace("SomeOtherClassInSameNamespace", "SomeClass"),
                               true, true);
    var rowList = gridRow.GetProperties(BindingFlags.Public | BindingFlags.Static)
                         .Where(p => p.PropertyType.Name.Contains("IBy"));
    
    int i = 0;
    foreach (var property in rowList)
    {
        string test = property.GetValue(null, null).ToString();
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多