c# - 将 "TYPE"传递给 Generic_Interface 类型的属性

标签 c# generics dependency-injection ninject

抓破我的秃头....我有一个通用的界面

interface IGenericInterface<T>
{
    T GenericTypeProperty {get; set;}
    void PerformService(); 
}

我有实现通用接口(interface)并做一些事情的服务器类

public class ServeRich : IGenericInterface<RichPeople>
{
    RichPeople GenericTypeProperty {get; set;}
    void PerformService() { //Serving the rich } 
}

public class ServePoor : IGenericInterface<PoorPeople>
{
    PoorPeople GenericTypeProperty {get; set;}
    void PerformService() { //Serving the Poor }
}

然后我有一个如下所示的服务类,我想调用其中一个服务器类并将其分配给并调用 PerformService()

public class ServeThem
{
    //This is where I am trying to figure out how to do this
    IGenericInterface<T<-??> Server {get; set;}

}

我想最终创建服务类并在服务器上调用执行服务方法....类似这样

main()
{
    ServeThem service= new ServeThem();
    service.Server = new ServePoor(); //This will be resolved by Ninject
    service.Server.PerformService();
}

我的问题在 IGenericInterface<T<-??> Server {get; set;} .我想弄清楚如何声明 Server属性作为通用接口(interface)类型,可以分配给实现特定类型接口(interface)的类的对象。似乎是为了声明 IGenericInterface<type> ,必须提及实际的具体类型。我尝试添加 passedInType属性(property)和使用typeof(passedInType)但这会引发异常。

如何将属性声明为通用接口(interface)类型?这可能吗?

最佳答案

您的服务中似乎没有使用GenericTypeProperty,因此您可以将PerformService 方法移动到非通用接口(interface)并在服务等级

interface INonGenericInterface
{
    void PerformService(); 
}

interface IGenericInterface<T>: INonGenericInterface
{
    T GenericTypeProperty {get; set;}
}

public class ServeThem
{
    INonGenericInterface Server {get; set;}
}

关于c# - 将 "TYPE"传递给 Generic_Interface 类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32894965/

相关文章:

c# - 我怎么能对文字字符串参数施加约束

c# - WPF 将网格背景设置为资源图像

c# - 如何设置项目的可执行进程名?

c# - 如何在不引发父事件的情况下为子 MenuItem 设置单击事件?

c# - List<T> 只读,带有私有(private)集

spring - 如何使用 Spring resource.groovy 正确注入(inject) Grails 服务

dependency-injection - OAuthAuthorizationServerProvider 实现中的 Autofac 依赖注入(inject)

java - 从类型变量调用静态方法

c# - 运算符和泛型类

javascript - 类型错误 : Cannot read property 'get' of undefined Angularjs