【发布时间】:2020-06-11 20:38:14
【问题描述】:
此代码的目标是遍历多个嵌套类,并将任意整数乘以 2。提供了简单的示例,但是,示例将来会更复杂。
如何将对象更改为其基础类?当我遍历这个函数时,它会正确读取 OuterProduct 的类型,但 InnerProduct 读取为System.RuntimeType 类型时失败,下面给出错误
如何解决此代码以将所有嵌套整数乘以 2?
未知模块中发生了“System.StackOverflowException”类型的未处理异常。
class Program
{
static void Main(string[] args)
{
var test = new OuterProduct();
test.AmountSold = 5;
test.ProductName = "BookOuter";
test.InnerProduct = new InnerProduct();
test.InnerProduct.ProductNameInner = "BookInner";
test.InnerProduct.AmountSoldInner = 7;
ReadPropertiesTest.ReadPropertiesRecursive(test);
}
}
public class OuterProduct
{
public string ProductName { get; set; }
public int AmountSold { get; set; }
public InnerProduct InnerProduct { get; set; }
}
public class InnerProduct
{
public string ProductNameInner { get; set; }
public int AmountSoldInner { get; set; }
}
public static class ReadPropertiesTest
{
public static void ReadPropertiesRecursive(object test)
{
var type = test.GetType();
foreach (PropertyInfo property in type.GetProperties())
{
if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
{
property.SetValue(test, (int)(property.GetValue(test)) * 2);
}
if (property.PropertyType.IsClass && !(property.PropertyType == typeof(string)))
{
ReadPropertiesRecursive(property.PropertyType);
}
}
}
}
资源:
C#: How to get all public (both get and set) string properties of a type
【问题讨论】:
-
如果你的 int?属性为 null,转换为 int 将引发异常。您应该单独处理这种情况。此外,如果您的嵌套对象没有值,您还需要对
test进行一般的空检查(假设您在下面的答案中进行了更改) -
嗨@pinkfloydx33 感谢您的输入,请随时写答案,我可以发送积分!
标签: c# .net .net-core reflection