你能 return 一个 'anonymous struct' 吗?
Can you return an 'anonymous struct'?
此答案描述了在 C# 中构建 'an anonymous struct':Is there an equivalent C# syntax for C's inline anonymous struct definition?
var x = new { SomeField = 1, SomeOtherField = "Two" };
从方法中 return this 是否有效以避免必须显式定义结构?对该答案的评论说不,但那是 2011 年...
那不是 struct
,而是 C# 中的 Anonymous Type(编译器实际上将其实现为 class
)。匿名类型是在本地范围内声明的,您不能在 C# 中将其作为强类型 class 传递,因为它是编译器生成的 class。您的选择是使用 object
或 dynamic
作为 return 类型,但您仍然会丢失基础类型。
总结一下你的问题,答案很简单"not the way you want it to work"。
MSDN 说:
Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
所以你可以 return 它作为一个 object
但是之后你不能对它们做太多,除非你使用反射或动态。
如果您的真实意图是return多个值,请改用Tuple<...>
类型:
return Tuple.Create<int, string>(1, "Two");
此答案描述了在 C# 中构建 'an anonymous struct':Is there an equivalent C# syntax for C's inline anonymous struct definition?
var x = new { SomeField = 1, SomeOtherField = "Two" };
从方法中 return this 是否有效以避免必须显式定义结构?对该答案的评论说不,但那是 2011 年...
那不是 struct
,而是 C# 中的 Anonymous Type(编译器实际上将其实现为 class
)。匿名类型是在本地范围内声明的,您不能在 C# 中将其作为强类型 class 传递,因为它是编译器生成的 class。您的选择是使用 object
或 dynamic
作为 return 类型,但您仍然会丢失基础类型。
总结一下你的问题,答案很简单"not the way you want it to work"。
MSDN 说:
Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
所以你可以 return 它作为一个 object
但是之后你不能对它们做太多,除非你使用反射或动态。
如果您的真实意图是return多个值,请改用Tuple<...>
类型:
return Tuple.Create<int, string>(1, "Two");