gpt4 book ai didi

c# - 访问 C# 匿名类型对象

转载 作者:可可西里 更新时间:2023-11-01 08:14:58 26 4
gpt4 key购买 nike

我如何访问其声明范围之外的匿名类型的对象?

例如

void FuncB()
{
var obj = FuncA();
Console.WriteLine(obj.Name);
}

??? FuncA()
{
var a = (from e in DB.Entities
where e.Id == 1
select new {Id = e.Id, Name = e.Name}).FirstOrDefault();

return a;
}

最佳答案

正如其他答案所述,你真的不应该这样做。但是,如果你坚持,那么有一个被称为“以身作则”的讨厌的技巧可以让你做到这一点。该技术在几篇文章中有所提及,herehere .

public void FuncB()
{
var example = new { Id = 0, Name = string.Empty };

var obj = CastByExample(FuncA(), example);
Console.WriteLine(obj.Name);
}

private object FuncA()
{
var a = from e in DB.Entities
where e.Id == 1
select new { Id = e.Id, Name = e.Name };

return a.FirstOrDefault();
}

private T CastByExample<T>(object target, T example)
{
return (T)target;
}

(虽然 the author of one of those articles says that he doesn't want to be associated with it either ,但我不能把这个黑客归功于此。他的名字可能很熟悉。)

关于c# - 访问 C# 匿名类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/713521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com