[英]Dynamically casting in C# recursively with Reflection
如何通过Reflection
类型转换将对象转换为其类型? 我已经在互联网上搜索了此问题,找到了一些方法,但它们不适合我的问题。 这是我的代码,我需要在类中强制转换其他动态类型的字段。
如果您看到以下代码,您会发现我为每个字段强制转换添加了四个if
。 我正在寻找一种方法来重构这堆更少的代码行。
public void CheckObjectFormatValues(object o)
{
FieldInfo[] fields = o.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (System.Reflection.FieldInfo prp in fields)
{
if (prp.FieldType.BaseType != typeof(ValueType))
{
if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ArrivalType")
CheckObjectFormatValues((ArrivalType)prp.GetValue(o));
if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.Cell")
CheckObjectFormatValues((Cell)prp.GetValue(o));
if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ObjectType")
CheckObjectFormatValues((ObjectType)prp.GetValue(o));
if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ObjAction")
CheckObjectFormatValues((ObjAction)prp.GetValue(o));
}
else
{
var value = prp.GetValue(o).ToString();
if (value == "-1")
throw new Exception("Error");
}
}
}
有什么方法可以使用递归函数重构If
块并动态转换?
根本不需要强制转换,您的方法将object
作为其参数
public void CheckObjectFormatValues(object o)
{
FieldInfo[] fields = o.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (System.Reflection.FieldInfo prp in fields)
{
if (prp.FieldType.BaseType != typeof(ValueType))
{
if(ShouldRecurse(prp.FieldType))
CheckObjectFormatValues(prp.GetValue(o));
}
else
{
var value = prp.GetValue(o).ToString();
if (value == "-1")
throw new Exception("Error");
}
}
}
private bool ShouldRecurse(Type fieldType)
{
// TODO
}
如您所见,您所需要的只是一些逻辑,以确定在给定Type
( FieldType
)的情况下该方法是否应自行调用。 您可以使用类上的属性,共享接口或任何其他方式来执行此操作。
就个人而言,我将使用以下属性:
public class RequiresCheckObjectFormatValuesAttribute: Attribute
{}
[RequiresCheckObjectFormatValues]
public class ArrivalType{ ... }
[RequiresCheckObjectFormatValues]
public class Cell{ ... }
然后,您的ShouldRecurse
方法很简单:
public bool ShouldRecurse(Type fieldType)
{
return fieldType.GetCustomAttributes<RequiresCheckObjectFormatValuesAttribute>().Length>0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.