c# - 在 C# 中使用 "Type"对象类型转换对象

标签 c# reflection casting types boxing

到目前为止,这对我来说有点棘手。我想知道是否可以使用 System.Type 对象对对象进行类型转换。

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

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();

上面是一个通用接口(interface),这就是我使用“对象”作为类型的原因。

最佳答案

这样做的典型方法是使用泛型,如下所示:

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 documentation for Generics here ,文章“Differences Between C++ Templates and C# Generics (C# Programming Guide)”可能会有帮助。

最后,我可能误解了您想在方法体内做什么:我不确定您如何将任意类型 T 转换为另一个任意类型 T2,除非您指定对泛型类型的约束。例如,您可能需要指定它们都必须实现某个接口(interface)。 Constraints on Type Parameters (C# Programming Guide)描述了如何在 C# 中执行此操作。

编辑:鉴于您修改后的问题,我认为this answer from Marco M.是正确的(也就是说,我认为您应该在当前尝试使用 IDataAdapter 接口(interface)的地方使用 Converter 委托(delegate)。)

关于c# - 在 C# 中使用 "Type"对象类型转换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1374440/

相关文章:

c# - Entity Framework 存储过程表值参数

c# - 有关使用最新.Net技术开发基于Web的新应用程序的建议

c# - 使用 while(true) 定期执行任务

c# - 确定谁触发了事件

java - 无法从 .class 读取注释

c# - ASP.net UserControl 和 AppDomain TypeResolve

c# - 我如何在 C# 中将 List<Interface> 转换为 List<Class>

java - Java中 "Unchecked cast"警告的解释

c# - 获取一个类型的所有派生类型

c++ - 为什么 (int&)0 格式不正确?