lundi 13 juillet 2015

c# Method with generic return type but not generic input. Is this possible?

Suppose we have a NodeData class:

public class NodeData<T>
{
    public string Name;
    public T Value;
    public NodeData(string name, T value)
    {
        this.Name = name;
        this.Value = value;
    }
}

And a Node class that has several properties with type NodaData:

public class Node
{
    public NodeData<int> data;
    public NodeData<double> data2;
    public NodeData<double> data3;
    public Node()
    {
        data = new NodeData<int>("test", 111);
        data2 = new NodeData<double>("test", 113);
    }
    public List<NodeData<T>> listOutputs<T>()
    {
        var fieldInfos = GetType().GetFields();
        var list = new List<NodeData<T>>();
        foreach (var item in fieldInfos)
        {
            Type t = item.FieldType;
            string name = item.Name;
            if (t == typeof(NodeData<T>))
            {
                var output = new NodeData<T>(name, default(T));
                list.Add(output);
            }
        }
        return list;
    }
}

As you can see there is a method which lists all outputs with type T in the Node class:

Node node = new Node();
var list = node.listOutputs<int>(); // this returns data

But I need to know how to use this method to list all NodeOutputs of any type T. In this example int and double. Do I need to add a class with this signature public List<NodeData<T>> listOutputs() // should return all properties data, data2, data3. Is it possible to have method like this? return type is generic but there is no type argument for method.





Aucun commentaire:

Enregistrer un commentaire