2009-03-06 2 views
1

Google 소프트웨어를 통해 생성 한 모든 사용자 정의 문서를 열 수있는 뷰어를 개발 중입니다. 모든 문서는 IDocument에서 상속 받지만 deserialize하는 방법에 대해서는 확신하지 못합니다 (좋은 방법으로 중첩 된 try/catch는 작동 할 수 있지만 그럴 수는 있습니다).런타임시 여러 유형 (알 수없는 유형)으로 캐스팅

은 그래서 지금처럼 내 방법은 다음과 같습니다 분명 내가 변수 DOCTYPE 방법을 사용할 수 없기 때문에이 작동하지 않습니다,하지만 난 그것의 요점을 설명 생각

public Boolean OpenDocument(String filename, Type docType, out IDocument document) 
{ 
    // exception handling etc. removed for brevity 

    FileStream fs = null; 
    BinaryFormatter bFormatter = new BinaryFormatter(); 

    fs = new FileStream(filename, FileMode.Open); 
    document = (docType)bFormatter.Deserialize(fs); 

    return true; 
} 

를 내가 나는하려고 애쓰다. 그것에 대해 알맞은 방법은 무엇입니까?

편집> @ 존 좋아, 어쩌면 내가 또 다른 질문 추가한다 :

public interface IDocument 
{ 
    public Int32 MyInt { get; } 
} 

및 클래스 : 내가 인터페이스가있는 경우 를 IDocument에

public class SomeDocType : IDocument 
{ 
    protected Int32 myInt = 0; 
    public Int32 MyInt { get { return myint; } } 

    public Int32 DerivedOnlyInt; 
} 

내가 역 직렬화하는 경우를, DerivedOnlyInt가 객체의 일부가 될 것입니다. 예를 들어 비 직렬화 후에 SomeDocType으로 캐스팅 할 수 있습니다. 그러면 괜찮을까요?

답변

4

IDocument으로 전송하지 않는 이유는 무엇입니까? 정확한 유형의 주조가 여기에 있었을 때 어떤 이점이 있다고 생각합니까? 에 적절한 유형을 알고있는 호출자에 의존하는, 물론

public T OpenDocument<T>(String filename) where T : IDocument 
{ 
    using (FileStream fs = new FileStream(filename, FileMode.Open)) 
    { 
     BinaryFormatter bFormatter = new BinaryFormatter();  
     return (T) bFormatter.Deserialize(fs); 
    } 
} 

:

당신은 여기에 내가 제네릭을 사용하여, 그것을 써서 방법, 호출자가 강력한 형식의 방법으로 결과를 얻고 싶다면 컴파일 시간.

public IDocument OpenDocument(String filename) 
{ 
    using (FileStream fs = new FileStream(filename, FileMode.Open)) 
    { 
     BinaryFormatter bFormatter = new BinaryFormatter();  
     return (IDocument) bFormatter.Deserialize(fs); 
    } 
} 

편집 : 질문에 대한 편집에 대답하려면, 그래 파생 그렇지 않은 경우, 그들은 그래서 그냥 IDocument을 반환하는 방법을 사용 어쨌든 적당한 유형, 알고거야 방법이 없습니다 속성은 여전히 ​​존재할 것입니다. 형변환은 실제로 객체를 변경하지 않습니다. 단지 컴파일러가 적절한 유형임을 알고있는 참조를 얻는다는 의미입니다.

+0

제 일반적인 함수를 사용하여 직렬화 함수를 래핑합니다. 이것은 가장 좋은 방법입니다. IMHO – JoshBerke

+0

아주 좋네요. 이 경우 호출자는 문서 유형을 알 수 있습니다 (openfiledialog의 파일 확장자를 통해). 감사합니다 Jon –

+0

@ 존 이것은 XmlSerialization에 대해 작동하지 않는 것 같습니다. 질문과 답변을 얻을 수 있었지만 작동했지만 조금 불안해 보였습니다. 뭔가 빠졌습니까? http://stackoverflow.com/questions/1145791/xml-object-deserialization-to-interface – ahsteele

1

당신은 직렬화 스트림에 정보를 입력 포함하는 경우 BinaryFormatter 클래스를 사용하는, 그래서 당신은 DOCTYPE 변수 필요가 없습니다 당신은 쉽게 그것이 문서의 종류를 알아낼 수 있다면 (

public Boolean OpenDocument(String filename, out IDocument document) 
{ 
    // exception handling etc. removed for brevity 

    FileStream fs = null; 
    BinaryFormatter bFormatter = new BinaryFormatter(); 

    fs = new FileStream(filename, FileMode.Open); 
    document = (IDocument)bFormatter.Deserialize(fs); 

    return true; 
} 
1

을 즉 : 파일 헤더의 일부입니다.) 각 유형에 고유 한 비 직렬화에 대해 strategy을 갖는 것이 가장 쉽습니다.

관련 문제