简体   繁体   English

在编译时按类型推断接口

[英]Infer interface by type at compile time

Is there any way to infer an interface from an object based on its type. 有什么方法可以根据对象的类型从对象推断接口。 For instance if I had the following object: 例如,如果我有以下对象:

public class Person
{
  public string FirstName
  { get; set; }

  public string LastName
  { get; set; }
}

I would like to be able to infer this interface: 我希望能够推断出此接口:

public interface IPerson
{
  string FirstName
  { get; set; }

  string LastName
  { get; set; }
}

What I would like to do is be able to create a generic proxy factory, using reflection.emit, that adheres to the inferred interface at compile time. 我想做的是能够使用reflect.emit创建一个通用代理工厂,该工厂在编译时会遵循推断的接口。 I know that I could instead return a dynamic object with all the object's properties, but that is all handled at runtime vs. compilation. 我知道我可以返回一个具有所有对象属性的动态对象,但这都是在运行时与编译时处理的。

Edit 编辑

A little more explanation for what I'm trying to achieve. 关于我要实现的目标的更多解释。 I want to create a proxy class that has a method with a signature something like this: 我想创建一个代理类,该代理类的方法带有如下所示的签名:

public T GetProxyFor<U>(U SomeObject);

That way a user can call GetProxyFor(People) and get back a PeopleProxy object that would implement the properties of the People object (or any other object). 这样,用户可以调用GetProxyFor(People)并获取将实现People对象(或任何其他对象)的属性的PeopleProxy对象。 That way, someone using this code could call PeopleProxy.LastName and this would successfully compile, but a call to PeopleProxy.Age would result in an error when compiled since it doesn't exist. 这样,使用此代码的人可以调用PeopleProxy.LastName并且可以成功编译,但是对PeopleProxy.Age的调用在编译时会导致错误,因为它不存在。

I'm fairly new to Reflection and emitting, so what I'm wanting may not be possible. 我对反射和发射还很陌生,所以我想要的可能无法实现。

Basically, what you're asking for is to execute some code that creates the interface at compile time. 基本上,您要的是执行一些在编译时创建接口的代码。

Your options are: 您的选择是:

  1. Use something like T4. 使用类似T4的东西。 You can use that to generate C# code based on some input at compile time. 您可以使用它在编译时根据一些输入生成C#代码。
  2. Use F# type providers. 使用F#类型的提供程序。 That's basically exactly what you want: it can execute code at compile time and generate the interface right when you write the code that calls GetProxyFor() . 这基本上就是您想要的:它可以在编译时执行代码,并在编写调用GetProxyFor()的代码时立即生成接口。 But there is nothing like that in C#, so it would require you to switch to F# (at least for the part of your code that uses GetProxyFor() ). 但是C#中没有类似的东西,因此它要求您切换到F#(至少对于使用GetProxyFor()代码部分GetProxyFor() )。
  3. Think about the underlying problem behind this question (which you didn't tell us) and solve it in another way. 考虑这个问题(您没有告诉我们)背后的根本问题,并以另一种方式解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM