gpt4 book ai didi

c# - 反射获取 FieldInfo 对象的类型?

转载 作者:行者123 更新时间:2023-11-30 19:20:51 31 4
gpt4 key购买 nike

大家好,我需要访问类 SomeClass ,它被声明在 Wrapper 类中有一个私有(private)字段,使用反射到目前为止我已经能够获得私有(private)字段成员。我如何将它转换回其原始类型以便我可以访问它的属性和其他成员。

internal class Program
{
private static void Main(string[] args)
{
Wrapper wrap = new Wrapper
{
SOmeProperty = new SomeClass
{
Number = 007
}
};

Type type = wrap.GetType();
FieldInfo[] infos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

foreach (var item in infos)
{
}
}
}

internal class SomeClass
{
public int Number { get; set; }
}

internal class Wrapper
{
private SomeClass _tempSomeObj;

public SomeClass SOmeProperty
{
get
{
return _tempSomeObj;
}
set
{
_tempSomeObj = value;
}
}
}

最佳答案

我不知道我是否理解正确的问题。你想要私有(private)字段(支持字段)的类型??

然后您可以检查 FieldInfo 的 FieldType 属性....

像这样:

internal class Program
{
#region Methods

private static void Main(string[] args)
{
var wrap = new Wrapper { SOmeProperty = new SomeClass { Number = 007 } };
Type type = wrap.GetType();

FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var fieldInfo in fieldInfos)
{
if (fieldInfo.FieldType == typeof(SomeClass))
{
Console.WriteLine("Yap!");
}
}
}

#endregion
}

internal class SomeClass
{
#region Properties

public int Number { get; set; }

#endregion
}

internal class Wrapper
{
#region Properties

public SomeClass SOmeProperty { get; set; }

#endregion
}

关于c# - 反射获取 FieldInfo 对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5090224/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com