简体   繁体   English

如何在C#中将通用类转换为通用接口

[英]How to cast a generic class to a generic interface in C#

according to below definitions 根据以下定义

interface myin
{
    int id { get; set; }
}
class myclass:myin
{
    public int id { get; set; }
}
[Database]
public sealed class SqlDataContext : DataContext, IDataContext
{
    public SqlDataContext(string connectionString) : base(connectionString){}
    public ITable<IUrl> Urls
    {
        get { return base.GetTable<Url>(); }  //how to cast Table<Url> to ITable<IUrl>?
    }
    ...
}

Update: 更新:

public IEnumerable<IUrl> Urls
{
    get { return base.GetTable<Url>(); }
}

so by use above approach, i haven't Table class associated methods and abilities. 因此通过使用上述方法,我没有与Table类相关的方法和能力。 this is good solution or not? 这是一个好的解决方案吗? and why? 为什么呢?

In C# 3.0 and odler this is not easily possible - see also covariance and contravariance in C# 4.0. 在C#3.0和odler中,这不容易实现-另请参见C#4.0中的协方差和协方差

The problem is that Table<Url> implements the ITable<Url> interface - this part of the casting is easy. 问题在于Table<Url>实现了ITable<Url>接口-这部分的转换很容易。 The tricky bit is casting ITable<Url> to ITable<IUrl> , because these two types aren't actually related in any way... 棘手的是将ITable<Url>强制ITable<Url>ITable<IUrl> ,因为这两种类型实际上没有任何关联...

In C# before 4.0, there is no easy way to do this - you'll explicitly need to create a new implementation of ITable<..> for the right generic type (eg by delegation). 在4.0之前的C#中,没有简单的方法可以执行此操作-您将明确需要为正确的泛型类型(例如,通过委托)创建ITable<..>的新实现。 In C# 4.0, this conversion can be done as long as ITable is a covariant interface . 在C#4.0中,只要ITable协变接口 ,就可以完成此转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM