首页 > 解决方案 > 公开包含不同类型的相同接口的属性的通用接口

问题描述

我有一个通用接口,它需要一个属性(父),它是相同的接口,但类型不同。我将如何实现这一目标?

public interface IConfigurator<T1>
{
   string TableName { get; }
   PropertyMapper<T1> PropertyMap { get; }
   IConfigurator<T2> ParentConfigurator {get;set;}   // this line is not valid c# code
}

我可以通过以下方式实现相同的目标,但如果适用,我想利用 c# 的属性:

ITypeConfigurator<T> GetParent<T>();
void AddParent<T>(ITypeConfigurator<T> parent);

标签: c#

解决方案


最好只使用一个object

public interface IConfigurator<T>
{
     string TableName { get; }
     PropertyMapper<T> PropertyMap { get; }
     object ParentConfigurator {get;set;} 
}

因为如果你在这条通用路径上走得太多了,它会变得有点混乱

public interface IConfigurator<T,TParent>
{
     string TableName { get; }
     PropertyMapper<T> PropertyMap { get; }
     IConfigurator<TParent,??> ParentConfigurator { get; } // what are you going to put here for ?? object maybe
}

除非你制作另一个界面

public interface IConfigurator<T>
{
     string TableName { get; }
     PropertyMapper<T> PropertyMap { get; }
}

public interface IConfigurator<T,TParent> : IConfigurator<T>
{
   IConfigurator<TParent> ParentConfigurator { get; } // what are you going to put here for ?? object maybe
}

推荐阅读