是否有.NET库,它可以发出.NET代码来创建代理类型?

时间:2011-05-24 20:53:23

标签: .net

观察以下代码段:

  public class SomeType
  {
    public SomeType2 X { get; set; }
    public int Y { get; set; }
  }

  public class SomeType2
  {
    public string Z { get; set; }
  }

  public class SomeTypeSurrogate
  {
    public static implicit operator SomeTypeSurrogate(SomeType obj) { return new SomeTypeSurrogate { X = obj.X, Y = obj.Y }; }
    public static implicit operator SomeType(SomeTypeSurrogate surrogate) { return new SomeType { X = surrogate.X, Y = surrogate.Y }; }
    public SomeType2Surrogate X { get; set; }
    public int Y { get; set; }
  }

  public class SomeType2Surrogate
  {
    public static implicit operator SomeType2Surrogate(SomeType2 obj) { return new SomeType2Surrogate { Z = obj.Z }; }
    public static implicit operator SomeType2(SomeType2Surrogate surrogate) { return new SomeType2 { Z = surrogate.Z }; }
    public string Z { get; set; }
  }

我的问题是有一个.NET库,它可以生成代理类型,如示例中给出的“真实”类型的描述以及必须在代理中找到的属性?

例如,一个虚构的代码可能看起来像这样(我的灵感来自protobuf-net的RuntimeTypeModel):

var model = new TypeSurrogateModel();
model.SetSurrogateNameScheme(SurrogateNameScheme.AddSuffix, "Surrogate");
model.AddType(typeof(SomeType), "X", "Y");
model.AddType(typeof(SomeType2), "Z");
model.Compile("Surrogates.dll");
...
var model = new TypeSurrogateModel();
model.AddAssembly("Surrogates.dll");
SomeType obj = GetSomeTypeInstance();
object surrogate = model.GetSurrogate(obj);
Debug.Assert(surrogate.GetType().Name == "SomeTypeSurrogate");

在使用代理人构建程序集之前:

var model = new TypeSurrogateModel();
model.SetSurrogateNameScheme(SurrogateNameScheme.AddSuffix, "Surrogate");
model.AddType(typeof(SomeType), "X", "Y");
model.AddType(typeof(SomeType2), "Z");
model.GenerateSource("Surrogates.cs");

在创建和编译Surrogates.cs之后,转向以常规类型安全方式使用它的程序集:

SomeType obj = GetSomeTypeInstance();
SomeTypeSurrogate surrogate = obj;

0 个答案:

没有答案