[英]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: 您的选择是:
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()
). GetProxyFor()
代码部分GetProxyFor()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.