source

문자열에서 다음으로 변환

nicesource 2023. 10. 6. 21:44
반응형

문자열에서 다음으로 변환

저는 정말로 이것을 받을 수 있어야 하는데, 지금은 좀 더 쉽게 물어볼 수 있을 것 같습니다.

C# 함수에서:

public static T GetValue<T>(String value) where T:new()
{
   //Magic happens here
}

마법에 좋은 구현 방법은 무엇입니까?이 배경에 있는 아이디어는 구문 분석할 xml이 있고 원하는 값은 종종 프리미티브(bool, int, string 등)이며 여기가 제네릭을 사용하기에 완벽한 장소라는 것입니다.하지만 간단한 해결책은 지금 나를 피하고 있습니다.

그건 그렇고, 여기 제가 분석해야 할 xml의 샘플이 있습니다.

<Items>
    <item>
        <ItemType>PIANO</ItemType>
        <Name>A Yamaha piano</Name>
        <properties>
            <allowUpdates>false</allowUpdates>
            <allowCopy>true</allowCopy>
        </properties>   
    </item>
    <item>
        <ItemType>PIANO_BENCH</ItemType>
        <Name>A black piano bench</Name>
        <properties>
            <allowUpdates>true</allowUpdates>
            <allowCopy>false</allowCopy>
            <url>www.yamaha.com</url>
        </properties>
    </item>
    <item>
        <ItemType>DESK_LAMP</ItemType>
        <Name>A Verilux desk lamp</Name>
        <properties>
            <allowUpdates>true</allowUpdates>
            <allowCopy>true</allowCopy>
            <quantity>2</quantity>
        </properties>
    </item>
</Items>

XML을 직접 구문 분석하는 대신 XML에서 클래스로 역직렬화할 수 있는 클래스를 만들 것을 제안합니다.bendewey의 답변을 따를 것을 강력히 권합니다.

하지만 당신이 이것을 할 수 없다면, 희망이 있습니다.사용하시면 됩니다.

public static T GetValue<T>(String value)
{
  return (T)Convert.ChangeType(value, typeof(T));
}

이렇게 사용합니다.

GetValue<int>("12"); // = 12
GetValue<DateTime>("12/12/98");

대략 다음과 같이 시작할 수 있습니다.

TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
   return (T)converter.ConvertFrom(value);
}

색상이나 문화 문자열 등 특수한 유형의 속성을 구문 분석해야 하는 경우, 물론 위에 특수한 경우를 구축해야 합니다.하지만 이것은 당신의 원시적인 타입의 대부분을 다룰 것입니다.

POCO(Plain old CLR Object)로 직렬화 경로를 선택한 경우 개체를 생성하는 데 도움이 되는 몇 가지 도구가 있습니다.

  • xsd를 사용할 수 있습니다.XML 정의를 기반으로 .cs 파일을 생성하려면 다음과 같이 하십시오.
  • WCF REST Starter Kit Preview 2에는 HTML로 붙여넣기라는 새로운 기능이 있습니다.이 기능은 정말 멋지고 클립보드에 있는 HTML 블록을 가져다가 cs 파일에 붙여넣으면 xml을 CLR 객체로 변환하여 직렬화할 수 있습니다.

이것이 제대로 작동하려면 일반 메소드가 실제 작업을 전용 클래스에 위임해야 합니다.

뭐 이런 거.

private Dictionary<System.Type, IDeserializer> _Deserializers;
    public static T GetValue<T>(String value) where T:new()
    {
       return _Deserializers[typeof(T)].GetValue(value) as T;
    }

여기서 _Deserializer는 클래스를 등록하는 일종의 사전입니다.(obviously를 들어, 사전에 병렬화기가 등록되었는지 확인하려면 어느 정도 확인이 필요합니다.)

이 경우 T:new()는 개체를 생성할 필요가 없으므로 쓸모가 없습니다.

다시 한 번 말씀드리지만, 이렇게 하는 것은 아마도 나쁜 생각일 것입니다.

class Item 
{
    public string ItemType { get; set; }
    public string Name { get; set; }
}

public static T GetValue<T>(string xml) where T : new()
{
    var omgwtf = Activator.CreateInstance<T>();
    var xmlElement = XElement.Parse(xml);
    foreach (var child in xmlElement.Descendants())
    {
        var property = omgwtf.GetType().GetProperty(child.Name.LocalName);
        if (property != null) 
            property.SetValue(omgwtf, child.Value, null);
    }
    return omgwtf;
}

테스트 실행:

static void Main(string[] args)
{
    Item piano = GetValue<Item>(@"
        <Item>
            <ItemType />
            <Name>A Yamaha Piano</Name>
            <Moose>asdf</Moose>
        </Item>");
}

언급URL : https://stackoverflow.com/questions/732677/converting-from-string-to-t

반응형