Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 408. 자바와 닷넷의 제네릭 차이점 - 중간 언어 및 공변/반공변 처리
; https://www.sysnet.pe.kr/2/0/1581

.NET Framework: 743. C# 언어의 공변성과 반공변성
; https://www.sysnet.pe.kr/2/0/11513

닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환
; https://www.sysnet.pe.kr/2/0/13636

닷넷: 2345. C# - 배열 및 Span의 공변성
; https://www.sysnet.pe.kr/2/0/13973




C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환

짧은 제목으로 표현하기 좀 힘들군요. ^^; 예를 들어, 아래와 같이 인터페이스를 상속받는 타입의 경우,

public interface IData
{
}

public class DataImpl : IData { }

때로는 저 DataImpl 타입을 반환하는 제네릭 타입이 있을 것입니다.

static private Task<DataImpl> GetDataImplAsync()
{
    // Task.Run으로 해도 되지만, 테스트 프로젝트를 .NET Framework 4.0으로 맞추느라 Task.Factory를 사용
    Task<DataImpl> task = Task.Factory.StartNew<DataImpl>(() =>
    {
        DataImpl data = new DataImpl();
        return data;
    });

    return task;
}

문제는, 저런 경우 IData 인터페이스로 공통 처리할 수 있는 방법이 없습니다. 즉, 다음과 같이 인터페이스가 아닌, 구현 타입을 갖는 제네릭을 받아야 합니다. (이에 대해서는 전에 자세히 다룬 글이 있고, C# 4부터 인터페이스에 한해 공변을 지원하는 보완을 했습니다.)

// error CS0029: Cannot implicitly convert type 'System.Threading.Tasks.Task<DataImpl>' to 'System.Threading.Tasks.Task<IData>'
// Task<IData> data2 = GetDataImplAsync();

Task<DataImpl> data = GetDataImplAsync();

저런 제약 때문에 DataImpl 구현 클래스를 담은 어셈블리를 반드시 참조하거나, 아니면 Reflection을 써서 접근을 해야 합니다. 물론 이런 경우 Reflection보다는 dynamic을 쓰는 것이 더 좋은 선택입니다.

dynamic data = GetDataImplAsync();
IData iData = data.Result; // 인터페이스로 형변환




만약 dynamic을 쓰고 싶지 않다면 어떻게 해야 할까요? 어쩔 수 없이 그럴 때는 Reflection으로 접근해야 합니다. 그런데, 다시 한번 만약, ^^ Reflection 속도보다 빠르게 접근하고 싶다면 어떻게 해야 할까요? 이럴 때는 (역시 예전에 dynamic과 비교해 설명한) LCG를 사용하면 됩니다.

그래서 대충 이런 식으로 만들어 주면,

private static Dictionary<string, Func<object, object>> _taskResultFunc = new();

private static object GetDynamicResult(object objValue)
{
    Type type = objValue.GetType();

    if (_taskResultFunc.TryGetValue(type.FullName, out var resultFunc) == false)
    {
        PropertyInfo prop = type.GetProperty("Result");
        MethodInfo mi = prop.GetGetMethod();

        DynamicMethod dm = new DynamicMethod(
            Guid.NewGuid().ToString(),
            typeof(object), [typeof(object)], typeof(Program), false);

        ILGenerator il = dm.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Isinst, type);
        il.Emit(OpCodes.Callvirt, mi);
        il.Emit(OpCodes.Ret);

        resultFunc = (Func<object, object>)dm.CreateDelegate(typeof(Func<object, object>));
        _taskResultFunc[type.FullName] = resultFunc;
    }

    return resultFunc(objValue);
}

이후 대상을 직접 참조하지 않고도 인터페이스 형변환만으로 다룰 수 있습니다.

IData result = GetDynamicResult(objData) as IData;

설령 이렇게 구현 클래스가 추가돼도,

public class AttrImpl : IData { }

static private Task<AttrImpl> GetAttrImplAsync()
{
    Task<AttrImpl> task = Task.Factory.StartNew<AttrImpl>(() =>
    {
        AttrImpl data = new AttrImpl();
        return data;
    });

    return task;
}

마찬가지의 방식으로 다룰 수 있습니다.

object objAttr = GetAttrImplAsync();
result = GetDynamicResult(objAttr) as IData;

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/17/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...
NoWriterDateCnt.TitleFile(s)
13629정성태5/18/202410813개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/202410071개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/202410246오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/202412007Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/202410656닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/202410465Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20249928닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/202412388닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/202411575오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/202410591VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/202411381닷넷: 2259. C# - decimal 저장소의 비트 구조 [1]파일 다운로드1
13618정성태5/6/202410074닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/202412350닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/202410054닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/202412354닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/202412082닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/202410242닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/202411711오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/202410436닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/202411726닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/202411553닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/202412191닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/202412167닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/202412111닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/202413693닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/202410099오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...