.NET 라이브러리 클래스로 사용자 지정 유형 변환을 주입합니다

StackOverflow https://stackoverflow.com/questions/606854

  •  03-07-2019
  •  | 
  •  

문제

CONVERN.CHANGETYPE를 통해 두 라이브러리 클래스 간의 전환을 구현하고 싶습니다. 두 가지 유형 중 어느 것도 변경할 수 없습니다. 예를 들어 Guid와 Byte 사이를 변환합니다 [].

Guid g = new Guid();
object o1 = g;
byte[] b = (byte[]) Convert.ChangeType(o1, typeof(byte[])); // throws exception

Guid가 TobyTearRay () 메소드를 제공한다는 것을 알고 있지만 Guid가 바이트로 변환 될 때 호출하고 싶습니다 []. 그 이유는 변환이 수정할 수없는 라이브러리 코드 (ASEDATAADAPTER)에서도 발생하기 때문입니다. 그렇다면 두 클래스 중 하나의 Sourcecode를 수정하지 않고 두 유형 사이의 변환 규칙을 정의 할 수 있습니까?

나는 typeconverter를 실험하고 있었지만 작동하지 않는 것 같습니다.

Guid g = new Guid();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Guid));
byte[] b2 = (byte[])tc.ConvertTo(g, typeof(byte[])); // throws exception

변수 tc는 byte []로의 변환을 지원하지 않는 System.componentModel.guidConverter로 설정됩니다. 동일한 클래스에 대해 두 개의 타이프 콘버터를 가질 수 있습니까? 가능하더라도 TypeConverter를 할당하기 위해 클래스의 소스 코드에 속성을 전제 할 필요가 없습니까?

감사

도움이 되었습니까?

해결책

등록 된 것을 변경할 수 있습니다 TypeConverter 사용하는 것 TypeDescriptor.AddAttributes; 이것은 거의 동일하지 않습니다 Convert.ChangeType, 그러나 충분할 수 있습니다 :

using System;
using System.ComponentModel;
static class Program
{
    static void Main()
    {
        TypeDescriptor.AddAttributes(typeof(Guid), new TypeConverterAttribute(
            typeof(MyGuidConverter)));

        Guid guid = Guid.NewGuid();
        TypeConverter conv = TypeDescriptor.GetConverter(guid);
        byte[] data = (byte[])conv.ConvertTo(guid, typeof(byte[]));
        Guid newGuid = (Guid)conv.ConvertFrom(data);
    }
}

class MyGuidConverter : GuidConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(byte[]) || base.CanConvertFrom(context, sourceType);
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(byte[]) || base.CanConvertTo(context, destinationType);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value != null && value is byte[])
        {
            return new Guid((byte[])value);
        }
        return base.ConvertFrom(context, culture, value);
    }
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(byte[]))
        {
            return ((Guid)value).ToByteArray();
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

다른 팁

System.ComponentModel.ICustomTypeDescriptor

예, 가능합니다. 관련 정보에 대한 관련 정보는 실행중인 프로그램에 MSDN의 문서를 읽으십시오. (Typedescriptor는 IIRC 메소드를 제공합니다).

변환을 수행하는 코드가 지원되는 경우 TypeConverter사용할 수 있습니다 TypeConverterAttribute 조립 수준에서.

불행히도 당신은 할 수 없습니다 - 당신은 확장 방법을 쓸 수 있습니다. 나타나다 프레임 워크의 일부로 두 가지 유형 사이의 변환이됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top