Код: Выделить всё
public interface IExample { }
public interface ISub1 { }
public interface ISub2 { }
public interface ICombined : IExample, ISub1 { }
public class TestGeneric where TBase : class, IExample
{
public void Example(T obj) where T : class, TBase
{
if (obj is ISub1 o1)
{
//The object must implement both IExample and ISub1 to enter this block
//Function(o1); //o1 does not implement IExample
//Function(obj); //obj does not implement ISub1
}
if (obj is ISub2 o2)
{
//The object must implement both IExample and ISub2 to enter this block
WorkingFunction(obj, o2);
}
if (obj is ICombined c)
{
//This works if the function is `Example where T: IExample`, but not `Example where T: TBase where TBase: IExample`
//Function(c);
}
}
private void Function(T obj) where T : class, TBase, ISub1
{
//Do stuff
}
private void WorkingFunction(T1 asExample, T2 asSub)
where T1 : class, TBase
where T2 : class, ISub2
{
//Do stuff - asExample and asSub are the same object, but implement different interfaces
}
}
Проблема в том, что актер для проверки объекта является ISUB1, дает переменную, которая только что напечатана как ISUB1, а также не iExample. Кодовый блок будет введен только в том случае, если объект реализует оба интерфейса, но я не могу найти способ сказать компилятору. При существующей конкретной реализации я могу просто сделать новый интерфейс, который реализует как iexample, так и iSub1 (
Код: Выделить всё
ICombinedПодробнее здесь: https://stackoverflow.com/questions/796 ... onstraints
Мобильная версия