这就是我需要做的事情:
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)
Qua*_*noi 14
你不能.C#没有实现duck typing.
您必须实现一个接口并强制转换为它.
(但是有人试图这样做.看看鸭子打字项目的例子.)
小智 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)
归档时间: |
|
查看次数: |
21340 次 |
最近记录: |