IT

객체를 실제 유형으로 캐스팅하는 방법은 무엇입니까?

lottoking 2020. 8. 20. 19:08
반응형

객체를 실제 유형으로 캐스팅하는 방법은 무엇입니까?


만약 내가 가지고 있다면 :

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

UPD :

이 당신을 위해 일할 수 있습니다.

void MyMethod(Object obj)
{
    if (obj is A)
    {
        A a = obj as A;
        ...
    } 
    else if (obj is B)
    {
        B b = obj as B;
        ...
    }
}

제 경우에는 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


실제 유형으로 변환하는 것은 수용.

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

귀하의 경우 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();

기능을 모르는 경우 다른 방식으로 수행 할 수 있습니다. 항상 쉽지는 않습니다. 그러나 서명으로 어떤 식 으로든 찾을 수 있습니다. 이것이 귀하의 경우라면 저희에게 알려 주셔야합니다.


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

참고 URL : https://stackoverflow.com/questions/12234097/how-to-cast-object-to-its-actual-type

반응형