C# 如何将 Object 转换为其实际类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12234097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast Object to its actual type?
提问by Paul Lassiter
If I have:
如果我有:
void MyMethod(Object obj) { ... }
How can I cast objto what its actual type is?
我怎样才能转换obj成它的实际类型?
采纳答案by Marc Gravell
If you know the actual type, then just:
如果您知道实际类型,则只需:
SomeType typed = (SomeType)obj;
typed.MyFunction();
If you don't know the actual type, then: not really, no. You would have to instead use one of:
如果您不知道实际类型,那么:不是真的,不是。您将不得不改用以下之一:
- reflection
- implementing a well-known interface
- dynamic
- 反射
- 实现一个众所周知的接口
- 动态的
For example:
例如:
// 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();
回答by user1610694
Casting to actual type is easy:
转换为实际类型很容易:
void MyMethod(Object obj) {
ActualType actualyType = (ActualType)obj;
}
回答by Maksim Vi.
I don't think you can (not without reflection), you should provide a type to your function as well:
我认为你不能(不是没有反射),你也应该为你的函数提供一个类型:
void MyMethod(Object obj, Type t)
{
var convertedObject = Convert.ChangeType(obj, t);
...
}
UPD:
更新:
This may work for you:
这可能对您有用:
void MyMethod(Object obj)
{
if (obj is A)
{
A a = obj as A;
...
}
else if (obj is B)
{
B b = obj as B;
...
}
}
回答by Hassan Boutougha
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 );
}
回答by devio
If your MyFunction()method is defined only in one class (and its descendants), try
如果您的MyFunction()方法仅在一个类(及其后代)中定义,请尝试
void MyMethod(Object obj)
{
var o = obj as MyClass;
if (o != null)
o.MyFunction();
}
If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:
如果在定义要调用的函数的不相关类中有大量定义,则应定义一个接口并使您的类定义该接口:
interface IMyInterface
{
void MyFunction();
}
void MyMethod(Object obj)
{
var o = obj as IMyInterface;
if (o != null)
o.MyFunction();
}
回答by Masoud
Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :
如果您现在的类型例如它是从名为 abc 的类定向的,则将其转换为实际类型。你可以这样调用你的函数:
(abc)(obj)).MyFunction();
if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.
如果您不知道该功能,则可以以不同的方式完成。总是不容易。但是你可以通过它的签名以某种方式找到它。如果这是你的情况,你应该让我们知道。
回答by Soren
In my case AutoMapper works well.
就我而言,AutoMapper 运行良好。
AutoMapper can map to/from dynamic objects without any explicit configuration:
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);
Similarly you can map straight from dictionaries to objects, AutoMapper will line up the keys with property names.
同样,您可以直接从字典映射到对象,AutoMapper 会将键与属性名称对齐。
more info https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping
更多信息https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping
回答by albin
How about JsonConvert.DeserializeObject(object.ToString());
怎么样 JsonConvert.DeserializeObject(object.ToString());
回答by bombek
This method might not be the most efficient but is simple and does the job.
这种方法可能不是最有效的,但很简单并且可以完成工作。
It performs two operations: firstly it calls .ToString() which is basiclly a serialization, and then the deserialization using Newtonsoft nuget (which you mustinstall).
它执行两个操作:首先它调用 .ToString() 这基本上是一个序列化,然后使用 Newtonsoft nuget(你必须安装)进行反序列化。
public T Format<T>(Object obj) =>
JsonConvert.DeserializeObject<T>(obj.ToString());

