到目前为止,这对我来说有点棘手。我想知道是否可以使用 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/