public abstract class Flattenable<T_Id, T_Order> where T_Id : struct, IComparable
where T_Order : IComparable
{
public abstract T_Id ID { get; }
public abstract Nullable<T_Id> Parent_ID { get; }
public abstract T_Order Order { get; }
}
partial class MyObjectClass : Flattenable<int, int>
{
public override int ID => this.My_Id;
public override int? Parent_ID => this.My_ParentId;
public override int Order => this.My_Ordinal;
}
public class FlatTree<T, T_Id, T_Order> where T : Flattenable<T_Id, T_Order>
where T_Id : struct, IComparable
where T_Order : IComparable
{
public FlatTree(IEnumerable<T> list)
{}
//Code using Flattenable .ID, Parent_ID , Order
}
In this code, I have an abstract class Flattenable
to extent an existing class with the necessery properties for my method to work.
My issue is that initialising my object I want the generik type to be some how "herited".
So One don't have to check MyObjectClass
definition for the Flattenable
generic type.
What I want var temp = new FlatTree<MyObjectClass>(myList);
.
Usage :
List<MyObjectClass> myList = GetItems();
var temp = new FlatTree<MyObjectClass,int,int>(myList); // => work
// What I want
var temp = new FlatTree<MyObjectClass>(myList); // => Sub type get sniffed from MyObjectClass.
var temp = new FlatTree(myList); // Sub type get sniffed from Enumerable T
CodePudding user response:
// What I want
var temp = new FlatTree(myList); // Sub type get sniffed from Enumerable T
Type inference does not work on constructors, because the constructor name is effectively the type of the object you're trying to instantiate.
The above syntax would be unable to resolve ambiguity if you codebase had existing class definitions for both FlatTree
and any generic FlatTree<>
; which supports the notion that constructors must explicitly specify all the generic types in order to identify the correct class.
// What I want
var temp = new FlatTree<MyObjectClass>(myList); // => Sub type get sniffed from MyObjectClass.
Even if you weren't dealing with constructors, partial type inference is currently not possible in C#. Type inference cannot complete a partial generic typing for you.
You have to specify the entire set of generic types to be used; or in cases where type inference works it means that you don't have to specify any generic type. There is no case where type inference only resolves some but not all of the generic types.