in the following code is an problem on line entities = doSpecialStuff(entities);
because i'm "missing" something in where part from my doSpecialStuff()
Methode
Error
The type 'T' cannot be used as type parameter 'T' in the generic type or method
'myWorkClass<T>.doSpecialStuff<T>(IEnumerable<T> entities)'. There is no implicit
reference conversion from 'T' to 'ISpezial'.)
Code
here are my ineritance structure
public class Baseclass { }
public interface ISpezial
{
int mySpecial{get;set;}
}
public class Class1 : Baseclass { }
public class Class2 : Baseclass, ISpezial
{
public int mySpecial{ get;set;}
}
here is my data provider
public class myRepository
{
public static IEnumerable<TResult> Load<TResult>() where TResult : Baseclass, new()
{
List<TResult> myEnum = new List<TResult>();
if (typeof(ISpezial).IsAssignableFrom(typeof(TResult)))
{
myEnum.Add((new Class2() { mySpecial = 0 }) as TResult);
myEnum.Add((new Class2() { mySpecial = 1 }) as TResult);
myEnum.Add((new Class2() { mySpecial = 2 }) as TResult);
}
else
{
myEnum.Add((new Class1() as TResult));
myEnum.Add((new Class1() as TResult));
myEnum.Add((new Class1() as TResult));
}
return myEnum;
}
}
and there it is the class who does stuff and provides errors like a boss
public class myWorkClass<T> where T : Baseclass, new()
{
public void doNormalStuff()
{
var entities = myRepository.Load<T>();
if (typeof(ISpezial).IsAssignableFrom(typeof(T)))
{
entities = doSpecialStuff(entities);
}
}
public IEnumerable<T> doSpecialStuff<T>(IEnumerable<T> entities) where T : ISpezial
{
var list = new List<T>();
return list.Where(special => special.mySpecial==2);
}
}
some further question
How can i avoid the new()
in my where's?
and how can i change the Add part myRepository
to do myEnum.Add(new Class1());
instead of myEnum.Add((new Class1() as TResult));
without changing the return IEnumerable<TResult>
?