是否可以将变量转换为存储在另一个变量中的类型?

Mar*_*icz 18 c# casting

这就是我需要做的事情:

object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?

GvS*_*GvS 20

您可以使用Convert.ChangeType方法.

object foo = GetFoo(); 
Type t = typeof(string);
string bar = (string)Convert.ChangeType(foo, t);
Run Code Online (Sandbox Code Playgroud)

  • 仅当对象实现IConvertible时,这才有用 (8认同)
  • 我只使用字符串作为例子.问题是我不知道目标类型所以我不能执行这个xyz bar =(xyz)Convert.Change ... cast. (4认同)

Qua*_*noi 14

你不能.C#没有实现duck typing.

您必须实现一个接口并强制转换为它.

(但是有人试图这样做.看看鸭子打字项目的例子.)

  • 您仍然需要实现接口(在这种情况下为IConvertible),并且事先知道要转换的类型. (2认同)

小智 5

由于在c#中加入了dynamics,我觉得我们可以这样做:

class Program {
    static void Main(string[] args) {
        List<int> c = new List<int>(); 
        double i = 10.0;
        Type intType = typeof(int);
        c.Add(CastHelper.Cast(i, intType)); // works, no exception!
    }
}

class CastHelper {
    public static dynamic Cast(object src, Type t) {
        var castMethod = typeof(CastHelper).GetMethod("CastGeneric").MakeGenericMethod(t);
        return castMethod.Invoke(null, new[] { src });
    }
    public static T CastGeneric<T>(object src) {
        return (T)Convert.ChangeType(src, typeof(T));
    }
}
Run Code Online (Sandbox Code Playgroud)