我有一个返回匿名类型的查询,并且该查询在一个方法中。你怎么写这个:
public "TheAnonymousType" TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new { SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return "TheAnonymousType";
}
}
你不能。
您只能返回 object
或对象容器,例如 IEnumerable<object>
、IList<object>
等。
您可以返回 dynamic
这将为您提供匿名类型的运行时检查版本,但仅限于 .NET 4+
在 C# 7 中,我们可以使用元组来完成此操作:
public List<(int SomeVariable, string AnotherVariable)> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new { SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB
.Select(s => (
SomeVariable = s.SomeVariable,
AnotherVariable = s.AnotherVariable))
.ToList();
}
}
您可能需要安装 System.ValueTuple
nuget 包。
{Item1: xxx, Item2: xxx}
等(如 - 名称丢失)
您不能返回匿名类型。你能创建一个可以返回的模型吗?否则,您必须使用 object
。
Here is an article written by Jon Skeet on the subject
文章中的代码:
using System;
static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}
Or, here is another similar article
或者,正如其他人评论的那样,您可以使用 dynamic
当需要返回时,您可以使用 Tuple 类代替匿名类型:
注意:元组最多可以有 8 个参数。
return Tuple.Create(variable1, variable2);
或者,对于原始帖子中的示例:
public List<Tuple<SomeType, AnotherType>> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select Tuple.Create(..., ...)
).ToList();
return TheQueryFromDB.ToList();
}
}
http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
(string mystring1, string mystring2, ...., string mystring42) myVar;
C# 编译器是一个两阶段编译器。在第一阶段,它只检查命名空间、类层次结构、方法签名等。方法主体仅在第二阶段编译。
在编译方法体之前,不会确定匿名类型。
所以编译器无法在第一阶段确定方法的返回类型。
这就是为什么匿名类型不能用作返回类型的原因。
正如其他人所建议的,如果您使用的是 .net 4.0 或更高版本,您可以使用 Dynamic
。
如果我是你,我可能会创建一个类型并从方法中返回该类型。这样,对于维护您的代码和更具可读性的未来程序员来说,这很容易。
三个选项:
选项1:
public class TheRepresentativeType {
public ... SomeVariable {get;set;}
public ... AnotherVariable {get;set;}
}
public IEnumerable<TheRepresentativeType> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB;
}
}
选项 2:
public IEnumerable TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB;
}
}
您可以将其迭代为对象
选项 3:
public IEnumerable<dynamic> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB; //You may need to call .Cast<dynamic>(), but I'm not sure
}
}
您将能够将其作为动态对象进行迭代并直接访问它们的属性
使用 C# 7.0 我们仍然无法返回匿名类型,但我们支持 元组类型,因此我们可以返回 tuple
的集合(在此案子)。当前为 Tuple types
are not supported in expression trees,您需要将数据加载到内存中。
您想要的最短代码版本可能如下所示:
public IEnumerable<(int SomeVariable, object AnotherVariable)> TheMethod()
{
...
return (from data in TheDC.Data
select new { data.SomeInt, data.SomeObject }).ToList()
.Select(data => (SomeVariable: data.SomeInt, AnotherVariable: data.SomeObject))
}
或者使用流利的 Linq 语法:
return TheDC.Data
.Select(data => new {SomeVariable: data.SomeInt, AnotherVariable: data.SomeObject})
.ToList();
.Select(data => (SomeVariable: data.SomeInt, AnotherVariable: data.SomeObject))
使用 C# 7.1 我们可以省略元组的属性名称,它们将从元组初始化中推断出来,就像它适用于匿名类型一样:
select (data.SomeInt, data.SomeObject)
// or
Select(data => (data.SomeInt, data.SomeObject))
在这种情况下,您可以返回对象列表。
public List<object> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new { SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB ;
}
}
public List<SomeClass> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new SomeClass{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB.ToList();
}
}
public class SomeClass{
public string SomeVariable{get;set}
public string AnotherVariable{get;set;}
}
创建自己的类并查询它是我所知道的最好的解决方案。据我所知,您不能在另一种方法中使用匿名类型返回值,因为它不会被识别。但是,它们可以在同一个方法中使用方法。我曾经将它们返回为 IQueryable
或 IEnumerable
,尽管它仍然无法让您看到匿名类型变量内部的内容。
我之前在尝试重构一些代码时遇到过类似的情况,您可以在此处查看:Refactoring and creating separate methods
您只能使用动态关键字,
dynamic obj = GetAnonymousType();
Console.WriteLine(obj.Name);
Console.WriteLine(obj.LastName);
Console.WriteLine(obj.Age);
public static dynamic GetAnonymousType()
{
return new { Name = "John", LastName = "Smith", Age=42};
}
但是使用动态类型关键字,您将失去编译时安全性、IDE IntelliSense 等...
用反射。
public object tst() {
var a = new {
prop1 = "test1",
prop2 = "test2"
};
return a;
}
public string tst2(object anonymousObject, string propName) {
return anonymousObject.GetType().GetProperties()
.Where(w => w.Name == propName)
.Select(s => s.GetValue(anonymousObject))
.FirstOrDefault().ToString();
}
样本:
object a = tst();
var val = tst2(a, "prop2");
输出:
test2
实际上可以从特定用例中的方法返回匿名类型。我们来看一下!
使用 C# 7 可以从方法返回匿名类型,尽管它带有轻微的约束。我们将使用一种称为 local function 的新语言特性和一个间接技巧(另一层间接可以解决任何编程挑战,对吧?)。
这是我最近确定的一个用例。从 AppSettings
加载所有配置值后,我想记录它们。为什么?因为有一些关于缺失值的逻辑可以恢复为默认值,一些解析等等。应用逻辑后记录值的一种简单方法是将它们全部放在一个类中并将其序列化到日志文件(使用 log4net)。我还想封装处理设置的复杂逻辑,并将其与我需要对它们做的任何事情分开。所有这些都无需创建仅用于一次性使用的命名类!
让我们看看如何使用创建匿名类型的本地函数来解决这个问题。
public static HttpClient CreateHttpClient()
{
// I deal with configuration values in this slightly convoluted way.
// The benefit is encapsulation of logic and we do not need to
// create a class, as we can use an anonymous class.
// The result resembles an expression statement that
// returns a value (similar to expressions in F#)
var config = Invoke(() =>
{
// slightly complex logic with default value
// in case of missing configuration value
// (this is what I want to encapsulate)
int? acquireTokenTimeoutSeconds = null;
if (int.TryParse(ConfigurationManager.AppSettings["AcquireTokenTimeoutSeconds"], out int i))
{
acquireTokenTimeoutSeconds = i;
}
// more complex logic surrounding configuration values ...
// construct the aggregate configuration class as an anonymous type!
var c = new
{
AcquireTokenTimeoutSeconds =
acquireTokenTimeoutSeconds ?? DefaultAcquireTokenTimeoutSeconds,
// ... more properties
};
// log the whole object for monitoring purposes
// (this is also a reason I want encapsulation)
Log.InfoFormat("Config={0}", c);
return c;
});
// use this configuration in any way necessary...
// the rest of the method concerns only the factory,
// i.e. creating the HttpClient with whatever configuration
// in my case this:
return new HttpClient(...);
// local function that enables the above expression
T Invoke<T>(Func<T> func) => func.Invoke();
}
我已经成功地构建了一个匿名类,并且还封装了处理复杂设置管理的逻辑,所有这些都在 CreateHttpClient
和它自己的“表达式”中。这可能不是 OP 想要的,但它是一种具有匿名类型的轻量级方法,目前在现代 C# 中是可能的。
另一种选择可能是使用自动映射器:只要公共属性匹配,您将从匿名返回的对象转换为任何类型。关键点是,返回对象,使用 linq 和 autommaper。 (或使用类似的想法返回序列化的json等或使用反射..)
using System.Linq;
using System.Reflection;
using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var data = GetData();
var firts = data.First();
var info = firts.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).First(p => p.Name == "Name");
var value = info.GetValue(firts);
Assert.AreEqual(value, "One");
}
[TestMethod]
public void TestMethod2()
{
var data = GetData();
var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
var users = data.Select(mapper.Map<User>).ToArray();
var firts = users.First();
Assert.AreEqual(firts.Name, "One");
}
[TestMethod]
public void TestMethod3()
{
var data = GetJData();
var users = JsonConvert.DeserializeObject<User[]>(data);
var firts = users.First();
Assert.AreEqual(firts.Name, "One");
}
private object[] GetData()
{
return new[] { new { Id = 1, Name = "One" }, new { Id = 2, Name = "Two" } };
}
private string GetJData()
{
return JsonConvert.SerializeObject(new []{ new { Id = 1, Name = "One" }, new { Id = 2, Name = "Two" } }, Formatting.None);
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}
现在尤其是使用本地函数,但是您总是可以通过传递一个创建匿名类型的委托来做到这一点。
因此,如果您的目标是在相同的源上运行不同的逻辑,并能够将结果组合到一个列表中。不确定为了实现既定目标而缺少什么细微差别,但只要您返回 T
并传递委托以制作 T
,您就可以从函数返回匿名类型。
// returning an anonymous type
// look mom no casting
void LookMyChildReturnsAnAnonICanConsume()
{
// if C# had first class functions you could do
// var anonyFunc = (name:string,id:int) => new {Name=name,Id=id};
var items = new[] { new { Item1 = "hello", Item2 = 3 } };
var itemsProjection =items.Select(x => SomeLogic(x.Item1, x.Item2, (y, i) => new { Word = y, Count = i} ));
// same projection = same type
var otherSourceProjection = SomeOtherSource((y,i) => new {Word=y,Count=i});
var q =
from anony1 in itemsProjection
join anony2 in otherSourceProjection
on anony1.Word equals anony2.Word
select new {anony1.Word,Source1Count=anony1.Count,Source2Count=anony2.Count};
var togetherForever = itemsProjection.Concat(otherSourceProjection).ToList();
}
T SomeLogic<T>(string item1, int item2, Func<string,int,T> f){
return f(item1,item2);
}
IEnumerable<T> SomeOtherSource<T>(Func<string,int,T> f){
var dbValues = new []{Tuple.Create("hello",1), Tuple.Create("bye",2)};
foreach(var x in dbValues)
yield return f(x.Item1,x.Item2);
}
var anonyFunc = (name:string,id:int) => new {Name=name,Id=id};
”:现在可以使用 C# 10 的 support for naturally typed lambdas
我不确定这个构造的名称,我认为这被称为匿名类型,但我可能错了。无论如何,我一直在寻找这个:
private (bool start, bool end) InInterval(int lower, int upper)
{
return (5 < lower && lower < 10, 5 < upper && upper < 10);
}
private string Test()
{
var response = InInterval(2, 6);
if (!response.start && !response.end)
return "The interval did not start nor end inside the target";
else if (!response.start)
return "The interval did not start inside the target";
else if (!response.end)
return "The interval did not end inside the target";
else
return "The interval is inside the target";
}
另一种调用方式可能是:
var (start, end) = InInterval(2, 6);
不定期副业成功案例分享
dynamic
。这使得它更容易使用。