Pau*_*ter 100 c# types casting typeof object
如果我有:
void MyMethod(Object obj) { ... }
Run Code Online (Sandbox Code Playgroud)
我obj该如何演绎其实际类型?
Mar*_*ell 166
如果您知道实际类型,那么只需:
SomeType typed = (SomeType)obj;
typed.MyFunction();
Run Code Online (Sandbox Code Playgroud)
如果你不知道实际的类型,那么:不是真的,不是.您将不得不使用以下之一:
例如:
// reflection
obj.GetType().GetMethod("MyFunction").Invoke(obj, null);
// interface
IFoo foo = (IFoo)obj; // where SomeType : IFoo and IFoo declares MyFunction
foo.MyFunction();
// dynamic
dynamic d = obj;
d.MyFunction();
Run Code Online (Sandbox Code Playgroud)
Mak*_*Vi. 39
我认为你不能(不是没有反思),你也应该为你的功能提供一个类型:
void MyMethod(Object obj, Type t)
{
var convertedObject = Convert.ChangeType(obj, t);
...
}
Run Code Online (Sandbox Code Playgroud)
UPD:
这可能对你有用:
void MyMethod(Object obj)
{
if (obj is A)
{
A a = obj as A;
...
}
else if (obj is B)
{
B b = obj as B;
...
}
}
Run Code Online (Sandbox Code Playgroud)
alb*_*bin 10
怎么样
JsonConvert.DeserializeObject<SomeType>(object.ToString());
Run Code Online (Sandbox Code Playgroud)