铸造类型有问题

时间:2012-02-03 14:54:01

标签: c# generics casting

我遇到了一个问题,即我无法将我的类转换为其父类型,并且不确定为什么这会考虑最终产品是相同的...是因为类是抽象的还是因为泛型类型在构造函数中指定?但是,我认为这个类的约束会解决这个问题吗?

很抱歉,如果我没有解释清楚,但我认为下面的代码可能会更详细地说明问题。

提前致谢,Onam。

public abstract class ClaimRepository<T> where T : WarrantyClaimBase 
{
    public ClaimRepository()
    { }

    public ClaimRepository(bool IncludeLabour, bool IncludeFranchiseLabour)
    {
    }

    protected abstract void GetFranchiseLabour();
}

public class TestClaimRepository : ClaimRepository<GWMWarrantyClaim>
{
    public TestClaimRepository()
    { }
    protected override void GetFranchiseLabour()
    {
        MessageBox.Show("Custom Implementation");
    }
}

public sealed class Factory
{
    public Factory()
    { }

    public ClaimRepository<WarrantyClaimBase> Get()
    {
        return new TestClaimRepository();
    }
}

2 个答案:

答案 0 :(得分:3)

我猜你从Factory.Get<T>()收到错误。您有一个约束,表示T必须从WarrantyClaimBase继承,但您返回的是更具体的类型。想想如果我写下会发生什么:

var factory = new Factory();
factory.Get<SomeOtherWarrantyType>();

代码有效,因为SomeOtherWarrantyType继承自WarrantyClaimBase,但TestClaimRepository显然无法转换为ClaimRepository<SomeOtherWarrantyType>。我建议您更改Get()的定义,因为您还没有使用T

public ClaimRepository<WarrantyClaimBase> Get() { }

答案 1 :(得分:1)

我假设您在这里收到编译错误:

public ClaimRepository<WarrantyClaimBase> Get()
{
    return new TestClaimRepository();
}

问题是TestClaimRepository继承自ClaimRepository<GWMWarrantyClaim>,而ClaimRepository<WarrantyClaimBase>不会继承ClaimRepository<GWMWarrantyClaim>

实际上,ClaimRepository<WarrantyClaimBase>从对象继承而且与继承层次结构的角度不再与string相关,而是与T : U相关。

对于泛型类型M,您似乎假设M<T> : M<U>暗示{{1}}。对于类来说,这是不正确的。 (如果ClaimRepository是一个接口,你可能可以逃脱这个。我建议阅读.NET中的协方差)