【问题标题】:c#: Interface needs to have a property off implementing class typec#: 接口需要有一个关闭实现类类型的属性
【发布时间】:2022-12-08 08:42:16
【问题描述】:

我需要有这样的东西。所以一个实现了这个接口的类需要得到一个与该类类型相同的属性。 这甚至可能吗,如果是的话怎么办?我正在使用.net 6。

public interface IProperty
{
    public typeof(this) parameter { get; } // doesn't work, can't use typeof() 
}   
public class clsResourceProperty : IProperty
{
    public clsResourceProperty  parameter { get; }
} 
public class clsInterfaceProperty : IProperty
{
    public clsInterfaceProperty  parameter { get; }
}

我知道如何使用通用接口,并且在第二个示例中它可以工作,但是 clsResourcePropertyGeneric: IPropertyGeneric 看起来很奇怪。并且不适用于我需要的应用程序。

public interface IPropertyGeneric<T>
{
    public T parameter { get; }
}
public class clsResourcePropertyGeneric: IPropertyGeneric<clsResourcePropertyGeneric>
{
    public clsResourcePropertyGeneric parameter { get; }
}
public class clsInterfacePropertyGeneric: IPropertyGeneric<clsInterfacePropertyGeneric>
{
    public clsInterfacePropertyGeneric parameter { get; }
}

在我需要的应用程序中,我需要有一个包含此接口列表的类。所以像这样:

public class clsState 
{
    public List<IProperty> data {get; private set;}
    public clsState(List<IProperty> data)
    {
        this.data = data;
    }
    public void logic()
    {
        foreach(var d in data) 
        {
            //do something with d.parameters
        }
    }
}

但这不适用于通用接口。我需要创建一个包含此接口列表的类,我在其中定义泛型类型 T。但是此列表不能包含实现此接口的所有类

public class clsState<T> 
// need to add T here to use it in the list, but the list needs to contain ALL implementing class types, not only 1
{
    public List<IProperty<T>> data {get; private set;}
    public clsState(List<IProperty<T>> data)
    {
        this.data = data;
    }
    public void logic()
    {
        foreach(var d in data) 
        {
            //do something with d.parameters
        }
    }
}

我找到了这个link,但这是 7 年前的,所以这方面可能有一些改进?

【问题讨论】:

  • 是的 C : I2&lt;C&gt; 看起来有点奇怪,但它完全符合您的要求!
  • 名字决定一切。public interface IDescendable&lt;T&gt; { T Parent { get; } } public class Folder: IDescendable&lt;Folder&gt; { public Folder Parent { get; } }

标签: c# .net class interface .net-6.0


【解决方案1】:

您可以使用该接口作为您的属性类型,如:

public interface IProperty
{
    public IProperty parameter { get; } 
}

public class clsResourceProperty : IProperty
{
    public IProperty parameter { get; }
}
public class clsInterfaceProperty : IProperty
{
    public IProperty parameter { get; }
}

至于拥有接口的集合,可以收集特定类型或接口的所有类。这是来自我的一个库中的一段代码。它并不完全符合您的要求,但它可能是迈向最终解决方案的一步。

private static Type[] strategyTypes;

private readonly static Type[] obsoleteTypes = new Type[]
{
};

static StrategyRepository()
{
    strategyTypes = Assembly.GetExecutingAssembly().GetTypes()
        .Where(t => t.BaseType == typeof(Strategy))
        .Except(obsoleteTypes)
        .ToArray();
}

这个问题可能是对你那部分问题的更直接的回答:Getting all types that implement an interface

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-26
    • 2011-02-11
    • 2014-01-18
    • 2013-12-09
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多