我有一个名为 A 的抽象类,以及实现 A 的其他类(B、C、D、E、...)
我还有一个 A 对象列表。
我希望能够将该列表中的每个对象动态转换为它们的“基本”类型(即 B、C、D 等),以便能够在其他方法中调用它们的构造函数。
这是我目前所做的:
abstract class A { }
class B : A { }
class C : A { }
class D : A { }
class E : A { }
// ...
class Program
{
static void Main(string[] args)
{
List<A> list = new List<A> { new B(), new C(), new D(), new E() };
// ...
foreach (A item in list)
{
A obj = foo(item);
}
}
public static A foo(A obj)
{
if (obj.GetType() == typeof(B))
{
return bar((B)obj);
}
else if (obj.GetType() == typeof(C))
{
return bar((C)obj);
}
// ... same for D, E, ...
return null;
}
public static T bar<T>(T obj) where T : class, new()
{
// To use the constructor, I can't have here an abstract class.
T newObj = new T();
return newObj;
}
它有效,但我想找到另一种方法,但要测试每个实现 A 的类是否它们的类型等于我的对象的类型,然后再转换它。
我有将近 15 个类(class),例如 B、C、D……而且我可能还有更多。 为了简单、清晰和可维护,我想避免使用这种方法,以及 15 种以上的“if(...) else(...)”。
你有办法做到这一点吗?
最佳答案
这样修改bar
:
public static T bar<T>(T obj) where T : class
{
var type = obj.GetType();
return Activator.CreateInstance(type) as T;
}
然后修改foo
:
public static A foo(A obj)
{
return bar(obj);
}
请注意,我必须删除 new()
约束。必须这样做以避免将 obj
转换到 foo
中。不过,您可以在运行时检查该类型是否具有无参数构造函数。
关于c# - 使用对象类型 C# 的动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14320952/