c# - 使用对象类型 C# 的动态转换

标签 c# reflection casting dynamic-cast

我有一个名为 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/

相关文章:

c# - 加载某些网站时出现 SSL 错误 "A call to SSPI failed"c#

c# - 将负数转换为无符号类型(ushort、uint 或 ulong)

java - 类型转换值(value)和由此产生的数学

c++ - int 到 bool 类型转换

c - 为什么这个显式转换的结果与隐式转换的结果不同?

c# - ASP.NET MVC 2 Html.TextAreaFor Html.TextArea 奇怪的绑定(bind)

c# - Visual Studio 2013 调试崩溃

java - 如何将看起来像数组的字符串转换为实际的对象数组?

c# - 在派生类中强制声明属性

c# - 如何找到包含等待/异步代码的间歇性失败单元测试的原因?