使用“ Type”类型转换对象。 C#中的对象

使用“ Type”类型转换对象。 C#中的对象

问题描述:

到目前为止,对我来说,这个技巧有些麻烦。我想知道是否可以使用System.Type对象进行类型转换。

This one has proven to be a little tricky for me so far. I am wondering if it is possible to type cast an object using a System.Type object.

我在下面说明了我的意思:

I have illustrated below what I mean:

public interface IDataAdapter
{
    object Transform(object input);
    Type GetOutputType();
}

public class SomeRandomAdapter : IDataAdapter
{
    public object Transform(object input)
    {
        string output;

        // Do some stuff to transform input to output...

        return output;
    }

    public Type GetOutputType()
    {
        return typeof(string);
    }
}

// Later when using the above methods I would like to be able to go...
var output = t.Transform(input) as t.GetOutputType();

以上是通用接口,这就是为什么我在类型上使用对象的原因。

The above is a generic interface which is why I am using "object" for the types.

典型的方法是使用泛型,例如:

The typical way to do that is to use generics, like so:

public T2 Transform<T, T2>(T input)
{
    T2 output;

    // Do some stuff to transform input to output...

    return output;
}

int    number = 0;
string numberString = t.Transform<int, string>(number);

正如您在下面的评论中提到的,泛型与C ++模板非常相似。您可以在此处找到泛型的MSDN文档,而文章 C ++模板与C#泛型之间的差异(《 C#编程指南》

As you mentioned in your comment below, generics are very similar to C++ Templates. You can find the MSDN documentation for Generics here, and the article "Differences Between C++ Templates and C# Generics (C# Programming Guide)" will probably be helpful.

最后,我可能会误解您要在方法体内执行的操作:我不确定如何转换 T 转换为另一个任意类型的 T2 ,除非您对通用类型指定了约束。例如,您可能需要指定它们都必须实现某个接口。 类型参数的约束(C#编程指南)描述了如何执行此操作

Finally, I might be misunderstanding what you want to do inside the method body: I'm not sure how you'll transform an arbitrary type T into another arbitrary type T2, unless you specify constraints on the generic types. For example, you might need to specify that they both have to implement some interface. Constraints on Type Parameters (C# Programming Guide) describes how to do this in C#.

编辑:鉴于您的已修订问题,我认为 Marco M的此答案。是正确的(也就是说,我认为您应该使用转换器代表,您当前正在尝试使用 IDataAdapter 接口。)

Edit: Given your revised question, I think this answer from Marco M. is correct (that is, I think you should use the Converter delegate where you're currently trying to use your IDataAdapter interface.)