Cle*_*ton 64 .net c# anonymous-types
我知道我不能写一个像这样的方法:
public var MyMethod()
{
return new{ Property1 = "test", Property2="test"};
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做:
public object MyMethod()
{
return new{ Property1 = "test", Property2="test"}
}
Run Code Online (Sandbox Code Playgroud)
但我不想做第二种选择,因为如果我这样做,我将不得不使用反射.
为什么我要这样做:
今天我在我的aspx页面中有一个方法返回一个数据表作为结果而我无法更改它,我试图将此DataTable转换为具有我想要使用的属性的Anonymous方法.我不想创建一个类只是为了这样做,因为我需要多次执行相同的查询,我想创建一个返回匿名类型的方法将是一个很好的意识形态.
And*_*are 65
将其作为a 返回是从方法返回匿名类型System.Object的唯一方法.不幸的是,没有其他方法可以做到这一点,因为匿名类型是专门为防止它们以这种方式使用而设计的.
你可以做一些技巧与返回一个Object让你接近的技巧.如果您对此解决方法感兴趣请阅读不能从方法返回匿名类型?真?.
免责声明:即使我链接的文章确实显示了一种解决方法,但并不意味着这样做是个好主意.我强烈建议您在创建常规类型时使用此方法更安全,更容易理解.
The*_*ght 26
或者,您可以在.NET 4.0及更高版本中使用Tuple类:
http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
Tuple<string, string> Create()
{
return Tuple.Create("test1", "test2");
}
Run Code Online (Sandbox Code Playgroud)
然后你可以访问这样的属性:
var result = Create();
result.Item1;
result.Item2;
Run Code Online (Sandbox Code Playgroud)
小智 19
public object MyMethod()
{
return new
{
Property1 = "test",
Property2 = "test"
};
}
static void Main(..)
{
dynamic o = MyMethod();
var p1 = o.Property1;
var p2 = o.Property2;
}
Run Code Online (Sandbox Code Playgroud)
bau*_*aur 13
作为替代方案,从C#7开始,我们可以使用ValueTuple.这里有一个小例子:
public (int sum, int count) DoStuff(IEnumerable<int> values)
{
var res = (sum: 0, count: 0);
foreach (var value in values) { res.sum += value; res.count++; }
return res;
}
Run Code Online (Sandbox Code Playgroud)
并在接收端:
var result = DoStuff(Enumerable.Range(0, 10));
Console.WriteLine($"Sum: {result.Sum}, Count: {result.Count}");
Run Code Online (Sandbox Code Playgroud)
要么:
var (sum, count) = DoStuff(Enumerable.Range(0, 10));
Console.WriteLine($"Sum: {sum}, Count: {count}");
Run Code Online (Sandbox Code Playgroud)
尽管有关于这是否是一个好主意的警告...... dynamic对于私人方法来说,似乎工作得很好.
void Main()
{
var result = MyMethod();
Console.WriteLine($"Result: {result.Property1}, {result.Property2}");
}
public dynamic MyMethod()
{
return new { Property1 = "test1", Property2 = "test2" };
}
Run Code Online (Sandbox Code Playgroud)
结果:test1,test2