我需要创建一个 2 类型的接口并将其用作方法返回值。
public interface StringLong<T1,T2>
where T1 : string
where T2 : long
{}
StringLong<T1,T2> method StringLong<T1,T2>()
我需要创建一个 2 类型的接口并将其用作方法返回值。
public interface StringLong<T1,T2>
where T1 : string
where T2 : long
{}
StringLong<T1,T2> method StringLong<T1,T2>()
用两个泛型类型定义一个接口是没有意义的,你只需要string
和long
。
听起来你只想要一个元组:
(string, long) MyMethod()
{
return ("Hello", 42L);
}
您甚至可以命名返回值:
(string message, long meaningOfLife) MyMethod()
{
return ("Hello", 42L);
}
然后你可以写:
var result = MyMethod();
Console.WriteLine(result.message);
Console.WriteLine(result.meaningOfLife);
我认为是您试图实现的功能(来自评论)。因为返回可能是string
或者long
有共同的祖先object
。
获得值后,您可以使用模式匹配将结果转换为适当的类型:
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";
}
}
}
另一种方法是创建您自己的共同祖先,例如Value
下面可能包含 along
和/或 a 的类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");
}
}
}