问题描述
方法和可能"如何从返回带有参数名称的元组类型的方法中返回,例如
How and "could be" organized return from the method which returns tuple type with the name of parameters,as an example
private static Tuple<string, string> methodTuple()
{
return new {Name = "Nick", Age = "Twenty"}; /*exception because need to new Tuple<string, string>(){Item1 = "Nick", Item2 = "Twenty"}o*/
}
并调用 methodTuple.Name
之类的参数,而不是 methodTuple.Item1 .... N
and call parameters like methodTuple.Name
not like methodTuple.Item1....N
这可能吗?
UPD:我想创建具有命名参数的对象,而没有新的命名类型.
UPD: I want to create object with named parameters without new named type.
推荐答案
您需要声明一个帮助程序类.
You need to declare a helper class to do so.
public class MyResult
{
public string Name { get; set; }
public string Age { get; set; }
}
您要返回的是匿名类型.顾名思义,您不知道它的名字,因此无法声明返回它的方法.
What you're trying to return is an anonymous type. As the name suggests you don't know what its name is, so you can't declare your method to return it.
更新
C#7引入了该语言内置的元组支持,并带有命名元组
C#7 introduces Tuple support built into the language and it comes with named tuples
(string name, int age) methodTuple()
{
(...)
}
在docs.microsoft.com上了解更多信息:https://docs.microsoft.com/zh-cn/dotnet/articles/csharp/csharp-7#tuples
Read more on docs.microsoft.com: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#tuples
这篇关于如何命名元组属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!