[英]How to use Generic interface with two type in return of method
I need to create an interface with 2 type and use it as a method return value.我需要创建一个 2 类型的接口并将其用作方法返回值。
public interface StringLong<T1,T2>
where T1 : string
where T2 : long
{}
StringLong<T1,T2> method StringLong<T1,T2>()
It makes no sense to define an interface with two generic types that you constrain to just string
and long
.用两个泛型类型定义一个接口是没有意义的,您将它们限制为
string
和long
。
It sounds like you just want a tuple:听起来你只想要一个元组:
(string, long) MyMethod()
{
return ("Hello", 42L);
}
You can even name the return values:您甚至可以命名返回值:
(string message, long meaningOfLife) MyMethod()
{
return ("Hello", 42L);
}
Then you can write:然后你可以写:
var result = MyMethod();
Console.WriteLine(result.message);
Console.WriteLine(result.meaningOfLife);
I think is the functionality you are trying to achieve (from the comments).我认为是您要实现的功能(来自评论)。 Since the return might be of either
string
or long
there common ancestor is object
.由于返回可能是
string
或long
,因此共同的祖先是object
。
Once you have the value you can use pattern matching to cast the result into the appropriate type:获得值后,您可以使用模式匹配将结果转换为适当的类型:
static class Program
{
static void Main(string[] args)
{
var obj = MethodReturnsStringOrLong(1722);
switch (obj)
{
case string str:
Console.WriteLine($"String is {str}");
break;
case long lng:
Console.WriteLine($"Long is {lng}");
break;
default:
throw new NotSupportedException();
}
}
public static object MethodReturnsStringOrLong(int input)
{
if (input % 2 == 0)
{
return 1928374028203384L;
}
else
{
return "ASIDJMFHSOASKSJHD";
}
}
}
An alternative is the create your own common ancestor, like the class Value
below that might contains either a long
and/or a string
.另一种方法是创建您自己的共同祖先,例如下面的 class
Value
,它可能包含一个long
和/或一个string
。
public class Value
{
public Value(long longValue)
{
LongValue = longValue;
}
public Value(string stringValue)
{
StringValue = stringValue;
}
public long? LongValue { get; }
public string StringValue { get; }
}
static class Program
{
static void Main(string[] args)
{
var obj = MethodReturnsStringOrLong(1722);
if (obj.LongValue.HasValue)
{
Console.WriteLine($"Long is {obj.LongValue.Value}");
}
if (!string.IsNullOrEmpty(obj.StringValue))
{
Console.WriteLine($"String is {obj.StringValue}");
}
}
public static Value MethodReturnsStringOrLong(int input)
{
if (input % 2 == 0)
{
return new Value(1928374028203384L);
}
else
{
return new Value("ASIDJMFHSOASKSJHD");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.