简体   繁体   中英

Generics without a specific type

I have this:

class Program
    {
        static void Main(string[] args)
        {

            var result = new Result<int, bool> { success = true, Data = 88 };
            var result2 = new Result<string, bool> { success = true, Data = "Niels" };


            Console.WriteLine(result2.success);
            Console.WriteLine(result2.Data);

            Console.ReadKey();
        }
    }

    public class Result<T, TU>
    {
        public TU success { get; set; }
        public T Data { get; set; }


    }

So this is a simple generic class with two properties.

I was just wondering, how to make this:

var result = new Result<int, bool> { success = true, Data = 88 };

even more generic :). Because you still have to "say" what the return type will be: <int, bool>

So is it possible to do it for example like this:

<T var1, T var2> ?

Thank you

So I mean like this:

var result = new Result<T var1, T var2> { success = true, Data = 88 };

So that you can fill in for success and for Data whatever you want(string, int , float, bool)..

You can use a factory method to resolve the types automatically from the given parameters:

public static class ResultFactory
{
    public static Result<T, TU> Create<T, TU>(TU success, T data)
    {
        return new Result<T, TU> { success = success, Data = data };
    }
}

var result = ResultFactory.Create(true, 88);
var result2 = ResultFactory.Create(true, "Niels");

Because you still have to "say" what the return type will be: <int, bool>

Yes you will have to specify the type T,TU and can't keep the type open. Types must be closed at compile time. Thus calling it like <T var1, T var2> won't be possible unless it's wrapped inside another generic type or method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM