【问题标题】:How do you define a property to hold a generic interface type?你如何定义一个属性来保存一个通用接口类型?
【发布时间】:2016-07-05 01:56:04
【问题描述】:

考虑如下界面...

public interface ILibraryService<T>
where T : Library
{
    ReadOnlyObservableCollection<T> AvailableLibraries { get; }
}

我想定义一个静态属性,它可以保存任何实现这个接口的对象,比如这个伪代码......

public static class Services
{
    public static ILibraryService<T> LibraryService { get; set; }
}

...但我不知道如何定义属性。我知道这很简单,但我只是没有看到它。

【问题讨论】:

  • 看起来完全正确。这不编译吗?
  • 不!自己试试吧!
  • Why does C# not allow generic properties? 的可能重复项。你说的对!每天学些新东西。我认为该线程非常详尽,

标签: c# generics interface


【解决方案1】:

这些是你所追求的吗?据我所知,Microsoft 故意避免让我们能够在属性上添加类型子句。

public static class Services
{
    public static ILibraryService<T> GetLibraryService<T>() 
        where T : Library
    {
        return null; // ...
    }
}

public static class Services<T>
    where T : Library
{
    public static ILibraryService<T> LibraryService { get; set; }
}

public static class Services<T>
    where T : ILibraryService<Library>
{
    public static T LibraryService { get; set; }
}

public static class Services<TService, TLibrary>
    where TService : ILibraryService<TLibrary>
    where TLibrary : Library
{
    public static ILibraryService<TLibrary> LibraryService { get; set; }
}

【讨论】:

  • Aaah... 在我意识到您的第一个示例是一个函数而不是一个属性之前,我很兴奋。不知道为什么当前者很好时他们会限制后者。但我想答案是我不能把它作为一个财产来做,这是我所希望的。
猜你喜欢
  • 2019-11-11
  • 2018-07-09
  • 2013-11-27
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 2013-12-09
  • 2021-05-16
  • 1970-01-01
相关资源
最近更新 更多