C# 重构:检查派生 class 的类型并分配给相同 class 的变量
C# Refactoring: check type of the derived class and assign to a variable of the same class
我有很多 class 是从一个抽象 class 派生出来的。在一个方法中,我收到一个对象,它是派生的 classes 之一。我需要检查对象的类型并分配给正确的 属性。直接的解决方案有效,但看起来可以重构。不过,我不知道如何处理它:
public MyDerived1 derived1;
public MyDerived2 derived2;
// ....
public MyDerivedX derivedX;
public void AssignValue(MyBaseClass entity)
{
var derivedOne = entity as MyDerived1;
if (derivedOne != null)
{
derived1 = derivedOne;
return;
}
var derivedTwo = entity as MyDerived2;
if (derivedTwo != null)
{
derived2 = derivedTwo;
return;
}
// ....
var derivedEx = entity as MyDerivedX;
if (derivedEx != null)
{
derivedX = derivedEx;
return;
}
}
您可以像这样创建 AssignValue
的通用版本:
private static bool AssignValue<T>(MyBaseClas entity, out T derived) where T : MyBaseClas
{
var t = entity as T;
if (t == null)
{
derived = null;
return false;
}
derived = t;
return true;
}
现在可以这样使用了:
MyDerived1 derived1;
MyDerived2 derived2;
var _ = AssignValue(entity, out derived1)
|| AssignValue(entity, out derived2);
通用函数 returns bool
跳过第一个匹配项的挂起类型检查
也许您正在寻找类似的东西:
public void AssignValue(MyBaseClass entity)
{
var item = this.GetType().GetFields().FirstOrDefault(x => x.FieldType == entity.GetType());
if (item != null)
{
item.SetValue(this, entity);
}
}
我有很多 class 是从一个抽象 class 派生出来的。在一个方法中,我收到一个对象,它是派生的 classes 之一。我需要检查对象的类型并分配给正确的 属性。直接的解决方案有效,但看起来可以重构。不过,我不知道如何处理它:
public MyDerived1 derived1;
public MyDerived2 derived2;
// ....
public MyDerivedX derivedX;
public void AssignValue(MyBaseClass entity)
{
var derivedOne = entity as MyDerived1;
if (derivedOne != null)
{
derived1 = derivedOne;
return;
}
var derivedTwo = entity as MyDerived2;
if (derivedTwo != null)
{
derived2 = derivedTwo;
return;
}
// ....
var derivedEx = entity as MyDerivedX;
if (derivedEx != null)
{
derivedX = derivedEx;
return;
}
}
您可以像这样创建 AssignValue
的通用版本:
private static bool AssignValue<T>(MyBaseClas entity, out T derived) where T : MyBaseClas
{
var t = entity as T;
if (t == null)
{
derived = null;
return false;
}
derived = t;
return true;
}
现在可以这样使用了:
MyDerived1 derived1;
MyDerived2 derived2;
var _ = AssignValue(entity, out derived1)
|| AssignValue(entity, out derived2);
通用函数 returns bool
跳过第一个匹配项的挂起类型检查
也许您正在寻找类似的东西:
public void AssignValue(MyBaseClass entity)
{
var item = this.GetType().GetFields().FirstOrDefault(x => x.FieldType == entity.GetType());
if (item != null)
{
item.SetValue(this, entity);
}
}