2012-02-03 114 views
2

我遇到了一个问题,我无法将我的课程转换为其父类型,并且不确定为什么这是考虑最终产品是相同的......是因为课程是抽象的还是由于在构造函数中指定的泛型类型?但是,我会认为对班级的限制会解决这个问题吗?铸造类型的麻烦

对不起,如果我没有解释得很好,但我认为下面的代码可能会更详细地说明问题。

在此先感谢,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(); 
    } 
} 
+3

你正在得到什么确切的错误?它是编译错误还是运行时错误? – 2012-02-03 14:56:16

+0

为什么当你不使用T时,你的类是通用的? – 2012-02-03 14:58:43

+0

我假设'GWMWarrantyClaim'继承自'WarrantyClaimBase'? – Strillo 2012-02-03 14:59:27

回答

3

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

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

的代码是有效的,因为从WarrantyClaimBaseTestClaimRepository明显SomeOtherWarrantyType继承不能被转换为ClaimRepository<SomeOtherWarrantyType>。我建议改变你的Get()定义,因为你不使用T反正:

public ClaimRepository<WarrantyClaimBase> Get() { } 
+0

+1好的解释和没有理由在这种情况下使用泛型参数。 – Yuck 2012-02-03 15:06:28

+0

是的,它的Factory.Get()方法导致我的问题,但通过改变它返回ClaimRepository 它没有返回我真正想要的类型...我以为因为TestClaimRepository继承ClaimRepository它应该可浇注吗? – 2012-02-03 15:31:28

+0

@Onam - 您可以将TestClaimRepository强制转换为WarrantyClaimBase,但正如我的示例中所述...您无法将TestClaimReository投射到ClaimRepository,如果您运行示例,将会发生什么情况。 – 2012-02-03 15:36:30

1

我假设你在这里得到编译错误:

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

的问题是,从ClaimRepository<GWMWarrantyClaim>TestClaimRepository继承,它不会从ClaimRepository<WarrantyClaimBase>继承。

实际上,从继承层次的角度来看,ClaimRepository<GWMWarrantyClaim>继承自对象,与ClaimRepository<WarrantyClaimBase>的关系不如string

您似乎认为T : U意味着M<T> : M<U>对于泛型类型M.对于类来说,这绝对是正确的。 (如果ClaimRepository是一个接口,你可能可以逃脱这一点,我推荐阅读.NET中的协变性)