반응형
WCF 역 직렬화는 생성자를 호출하지 않고 개체를 어떻게 인스턴스화합니까?
WCF 역 직렬화에는 몇 가지 마술이 있습니다. 생성자를 호출하지 않고 데이터 계약 형식의 인스턴스를 어떻게 인스턴스화합니까?
예를 들어 다음 데이터 계약을 고려하십시오.
[DataContract]
public sealed class CreateMe
{
[DataMember] private readonly string _name;
[DataMember] private readonly int _age;
private readonly bool _wasConstructorCalled;
public CreateMe()
{
_wasConstructorCalled = true;
}
// ... other members here
}
를 통해이 개체의 인스턴스를 가져 DataContractSerializer
오면 필드 _wasConstructorCalled
가 false
.
그렇다면 WCF는 어떻게 이것을합니까? 이것은 다른 사람들도 사용할 수있는 기술입니까, 아니면 우리에게서 숨겨져 있습니까?
FormatterServices.GetUninitializedObject()
생성자를 호출하지 않고 인스턴스를 생성합니다. Reflector 를 사용 하고 일부 핵심 .Net 직렬화 클래스 를 파헤쳐이 클래스를 찾았습니다 .
아래 샘플 코드를 사용하여 테스트했는데 잘 작동하는 것 같습니다.
using System;
using System.Reflection;
using System.Runtime.Serialization;
namespace NoConstructorThingy
{
class Program
{
static void Main()
{
// does not call ctor
var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));
Console.WriteLine(myClass.One); // writes "0", constructor not called
Console.WriteLine(myClass.Two); // writes "0", field initializer not called
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass ctor called.");
One = 1;
}
public int One { get; private set; }
public readonly int Two = 2;
}
}
http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png
Yes, FormatterServices.GetUninitializedObject() is the source of the magic.
If you want to do any special initialization, see this. http://blogs.msdn.com/drnick/archive/2007/11/19/serialization-and-types.aspx
반응형
'Program Tip' 카테고리의 다른 글
PHP Trait이 인터페이스를 구현할 수없는 이유는 무엇입니까? (0) | 2020.10.12 |
---|---|
바이트 배열에서 C #의 C / C ++ 데이터 구조 읽기 (0) | 2020.10.12 |
PHP의 클로저… 정확히 무엇이며 언제 사용해야합니까? (0) | 2020.10.12 |
log4j : WARN web.xml에서 로거에 대한 추가자를 찾을 수 없습니다. (0) | 2020.10.12 |
C ++에서 어떻게 'realloc'을 사용합니까? (0) | 2020.10.12 |