如果我有:
void MyMethod(Object obj) { ... }
我应该如何将obj
转换为其实际类型?
如果您知道实际类型,那么只需:
SomeType typed = (SomeType)obj;
typed.MyFunction();
如果你不知道实际的类型,那么 :不太行。你需要使用以下其中之一:
例如:
// 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();
as
进行类型转换和 type(of: ClassName)
函数来检查实例类型。 - Nagendra Rao我认为你不能这样做(没有反射的情况下),你还需要给你的函数提供一个类型:
void MyMethod(Object obj, Type t)
{
var convertedObject = Convert.ChangeType(obj, t);
...
}
更新:
这可能适用于您:
void MyMethod(Object obj)
{
if (obj is A)
{
A a = obj as A;
...
}
else if (obj is B)
{
B b = obj as B;
...
}
}
JsonConvert.DeserializeObject<SomeType>(object.ToString());
var myType = JsonConvert.DeserializeObject<MyType>(object.ToString());
- CokeMyFunction()
方法只在一个类(及其派生类)中定义,请尝试void MyMethod(Object obj)
{
var o = obj as MyClass;
if (o != null)
o.MyFunction();
}
interface IMyInterface
{
void MyFunction();
}
void MyMethod(Object obj)
{
var o = obj as IMyInterface;
if (o != null)
o.MyFunction();
}
另一个选择是将其序列化,然后将其反序列化为您想要的对象。
JsonConvert.DeserializeObject<OtherType>(JsonConvert.SerializeObject(obj));
public class Foo {
public int Bar { get; set; }
public int Baz { get; set; }
}
dynamic foo = new MyDynamicObject();
foo.Bar = 5;
foo.Baz = 6;
Mapper.Initialize(cfg => {});
var result = Mapper.Map<Foo>(foo);
result.Bar.ShouldEqual(5);
result.Baz.ShouldEqual(6);
dynamic foo2 = Mapper.Map<MyDynamicObject>(result);
foo2.Bar.ShouldEqual(5);
foo2.Baz.ShouldEqual(6);
如果您知道类型,可以将其转换为实际类型,例如它是从名为abc的类中派生的。 您可以这样调用函数:
(abc)(obj)).MyFunction();
如果您不知道该函数如何实现,可以用另一种方式来完成。这并不总是容易的,但您可以通过其签名找到它的某些方法。如果您遇到这种情况,请告诉我们。
void TheObliviousHelperMethod<T>(object obj) {
(T)obj.ThatClassMethodYouWantedToInvoke();
}
// Meanwhile, where the method is called:
TheObliviousHelperMethod<ActualType>(obj);
可以在圆括号后使用 where
关键字添加类型限制。
Implement an interface to call your function in your method
interface IMyInterface
{
void MyinterfaceMethod();
}
IMyInterface MyObj = obj as IMyInterface;
if ( MyObj != null)
{
MyMethod(IMyInterface MyObj );
}
obj.MyFunction();
无法编译,尽管我知道真正的对象确实有这个函数。 - Paul LassiterMyFunction
方法的是什么? - Jon Skeet