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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14320952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:25:37  来源:igfitidea点击:

Dynamic cast using Type of object C#

c#reflectioncastingdynamic-cast

提问by Sharpac

I have one abstract class named A, and other classes (B, C, D, E, ...) that implements A

我有一个名为 A 的抽象类,以及实现 A 的其他类(B、C、D、E...)

I also have a list of A objects.
I'd like to be able to cast dynamicly each of the object in that list to their "base" type (ie B, C, D, ...) to be able to call their constructor in an other method.

我也有一个 A 对象的列表。
我希望能够将该列表中的每个对象动态转换为它们的“基本”类型(即 B、C、D...),以便能够在其他方法中调用它们的构造函数。

Here is what I have done for now :

这是我现在所做的:

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;
    }

It works, but I'd like to find an other way but to test for each class that implements A if their type equals the type of my object, and cast it afterwards.

它有效,但我想找到另一种方法,但要测试每个实现 A 的类,如果它们的类型等于我的对象的类型,然后再进行转换。

I have nearly 15 classes like B, C, D, ... and I might have more. In order to have something simple, clear and maintainable, I'd like to avoid this methods, and the 15+ "if(...) else(...)".

我有将近 15 个班级,例如 B、C、D ……而且我可能还有更多。为了有一些简单、清晰和可维护的东西,我想避免这种方法,以及 15+ 的“if(...) else(...)”。

Do you see a way to do so ?

你看到了这样做的方法吗?

采纳答案by Mir

Modify barin this way:

这样修改bar

public static T bar<T>(T obj) where T : class
{
    var type = obj.GetType();
    return Activator.CreateInstance(type) as T;
}

Then modify foo:

然后修改foo

public static A foo(A obj)
{
    return bar(obj);
}

Note that I had to remove the new()constraint. That had to be done to avoid casting your objinside of foo. You can check at runtime if the type has a parameterless constructor, though.

请注意,我必须删除new()约束。必须这样做以避免将您的obj内部转换为foo. 不过,您可以在运行时检查该类型是否具有无参数构造函数。