开发者

How to cast a generic class to a generic interface in C#

开发者 https://www.devze.com 2023-01-15 07:08 出处:网络
according to below definitions interface myin { int id { get; set; } } class myclass:myin { public int id { get; set; }

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(c开发者_Python百科onnectionString){}
    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. 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.

The problem is that Table<Url> implements the ITable<Url> interface - this part of the casting is easy. The tricky bit is casting ITable<Url> to ITable<IUrl>, because these two types aren't actually related in any way...

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 (e.g. by delegation). In C# 4.0, this conversion can be done as long as ITable is a covariant interface.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号