如何命名元组属性? [英] How to name tuple properties?

查看:86
本文介绍了如何命名元组属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法和可能"如何从返回带有参数名称的元组类型的方法中返回,例如

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#编程指南)

您不能声明字段,属性,事件或返回类型具有匿名类型的方法.类似地,您不能声明方法,属性,构造函数或索引器的形式参数为具有匿名类型.传递匿名类型或集合包含匿名类型,作为方法的参数,您可以将参数声明为类型对象.但是,这样做会打败强力打字的目的.如果必须存储查询结果或将它们传递给在方法边界之外,请考虑使用普通的命名结构或类,而不是匿名类型.

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

更新

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

这篇关于如何命名元组属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆