[英]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>
因为您仍然必须“说”返回类型是什么:
<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>
因为您仍然必须“说”返回类型是什么:
<int, bool>
Yes you will have to specify the type T,TU
and can't keep the type open. 是的,您将必须指定
T,TU
类型T,TU
并且不能保持打开状态。 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 因此不可能像
<T var1, T var2>
那样调用它<T var1, T var2>
除非将它包装在另一个泛型类型或方法中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.