开发者

Generic class and downcasting (typecasting)

开发者 https://www.devze.com 2023-02-02 00:21 出处:网络
public interface ISomeDTOInterface { ... } public classSomeDTOClass : ISomeDTOInterface { ... } public interface DataStoreChanges<T>
public interface ISomeDTOInterface 
{
    ...
}

public class    SomeDTOClass : ISomeDTOInterface
{
    ...
}

public interface DataStoreChanges<T>
{
    IEnumerable<T> data {get;}
    IEnumerable<Guid> removedItems {get;}
    IEnumerable<Guid> newItems {get;}
    IEnumerable<Guid> modifiedItems {get;}
}

now I have a method which expects

DataStoreChanges<ISomeDTOInterface>

, so I try to pass an instance of DataStoreChanges<SomeDTOClass>, which generates a type error. It wont let me开发者_开发百科 downcast to the interface:) so whats wrong here.


In C# 4, you can make the interface covariant. To do this, change the interface declaration to:

public interface DataStoreChanges<out T>

Otherwise, you can make the method generic and add the relevant type constraint.

void SomeMethod<T> (DataStoreChanges<T> x)  where T : ICommonInterface
{
    ...
}


You're having issues because by default you're not specifying that the method should allow a more derived type of T, in that sense its not covariant. By changing your interface definition to:

public interface DataStoreChanges<out T> 

This will allow covariance.

If that is not possible, I guess you could also use a generic constraint on where T : ICommonInterface


I think you are lacking type constrains - but could you actually add the non-compiling code?

where T:ICommonInterface

But this is just an educated guess based on your other information.

0

精彩评论

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