繁体   English   中英

如何将 Object 转换为实际类型?

[英]How to cast Object to its actual type?

如果我有:

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();

我认为你不能(不是没有反射),你也应该为你的函数提供一个类型:

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;
        ...
    }
}

如果我有:

void MyMethod(Object obj) {   ...   }

如何将obj转换为实际类型?

就我而言,AutoMapper 运行良好。

AutoMapper 可以在没有任何显式配置的情况下映射到/从动态对象:

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);

同样,您可以直接从字典映射到对象,AutoMapper 会将键与属性名称对齐。

更多信息https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping

怎么样

JsonConvert.DeserializeObject<SomeType>(object.ToString());

你也可以使用模式匹配

void MyMethod(Object obj) {   

  if(obj is SomeType myVar){
    myVar.MyFunction();
  }
}

如果您的MyFunction()方法仅在一个类(及其后代)中定义,请尝试

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();
}

如果您现在的类型例如它是从名为 abc 的类定向的,则将其转换为实际类型。 你可以这样调用你的函数:

(abc)(obj)).MyFunction();

如果您不知道该功能,则可以以不同的方式完成。 总是不容易。 但是你可以通过它的签名以某种方式找到它。 如果这是你的情况,你应该让我们知道。

如果可能有多种类型,方法本身不知道要转换的类型,但调用者知道,您可能会使用以下内容:

void TheObliviousHelperMethod<T>(object obj) {
    (T)obj.ThatClassMethodYouWantedToInvoke();
}

// Meanwhile, where the method is called:
TheObliviousHelperMethod<ActualType>(obj);

可以使用括号后的where关键字添加对类型的限制。

另一种选择是将其序列化,然后将其反序列化为您想要的 object。 JsonConvert.DeserializeObject<OtherType>(JsonConvert.SerializeObject(obj));

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 );
}

转换为实际类型很容易:

void MyMethod(Object obj) {
    ActualType actualyType = (ActualType)obj;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM