具有多个返回参数的 C# 方法
c#/.net中是否需要多个返回参数?
public string, string GetFirstNameAndLastName(int id)
{
var person = from p in People
where p.Id = id
select p;
return(p.FirstName, p.LastName);
}
用法:
public void Main(string[] args)
{
string firstName, lastName;
(firstName, lastName) = GetFirstNameAndLastName(1);
Console.WriteLine(firstName + ", " + lastName);
}
Is there a need for multiple return parameters in c#/.net?
public string, string GetFirstNameAndLastName(int id)
{
var person = from p in People
where p.Id = id
select p;
return(p.FirstName, p.LastName);
}
Usage:
public void Main(string[] args)
{
string firstName, lastName;
(firstName, lastName) = GetFirstNameAndLastName(1);
Console.WriteLine(firstName + ", " + lastName);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不。如果元素相关,您应该返回更有用的数据类型,例如类。
No. You should return a more useful data type like a class if the elements are related.
除了其他答案中指出的可能性之外,还有更多方法可以实现这一点:
Next to the possibilities pointed out in other answers, there is are more ways to archieve this:
视情况而定。在您的情况下,您可以返回整个人的记录,
或者如果情况需要,您可以创建自己的数据类型。
Depends on the situation. In your case you could return the whole person record back,
or if the situation required it you could create your own data type.
您可以像这样做您想做的事:
然后像这样调用它:
You can do what you want like this:
and then call it like this:
您可以使用 C# 4.0 中的 Tuple 以轻量级方式实现此目的
System.Tuple
还具有与 F# 本机元组类型互操作的好处(嗯,它是 F# 的本机元组类型,只是恰好有 F# - 用于声明元组和返回元组的函数的特定语法支持)。鉴于这里存在多种方法:
System.Tuple
、多个out
参数或返回带有FirstName
和LastName
的POCO > 属性,我怀疑 Anders Hejlsberg 可能不会添加对多个返回值的显式支持。You can achieve this in a lightweight fashion using Tuple in C# 4.0
System.Tuple
also has the benefit of interoperating with F# native tuple type (well, it IS F#'s native tuple type, there just happens to be F#-specific syntax support for declaring tuples and functions that return them).Given the existence of multiple approaches here:
System.Tuple
, multipleout
parameters or returning a POCO withFirstName
andLastName
properties, I suspect that Anders Hejlsberg is probably not going to add explicit support for multiple return values.不,只需使用
out
参数即可。No, just use
out
parameters.根据@James Webster的建议,您可以使用元组或可以使用
dynamic
和ExpandoObject
As suggested by @James Webster you can use tuple or you can use
dynamic
andExpandoObject