注意
,根据注释,我只想指出,当您需要像这样在程序中传递实类型时,我也建议使用实类型。匿名类型实际上应该一次只在一种方法中本地使用(我认为),但是无论如何,这就是我剩下的答案。
您可以使用技巧,通过诱使编译器为您推断正确的类型:
using System;namespace ConsoleApplication4{ class Program { static void Main(string[] args) { var a = new { Id = 1, Name = "Bob" }; TestMethod(a); Console.Out.WriteLine("Press enter to exit..."); Console.In.ReadLine(); } private static void TestMethod(Object x) { // This is a dummy value, just to get 'a' to be of the right type var a = new { Id = 0, Name = "" }; a = Cast(a, x); Console.Out.WriteLine(a.Id + ": " + a.Name); } private static T Cast<T>(T typeHolder, Object x) { // typeHolder above is just for compiler magic // to infer the type to cast x to return (T)x; } }}诀窍在于,在程序集中,相同的匿名类型(相同的属性,相同的顺序)解析为相同的类型,从而使上述技巧起作用。
private static T CastTo<T>(this Object value, T targetType){ // targetType above is just for compiler magic // to infer the type to cast value to return (T)value;}用法:
var value = x.CastTo(a);
但是,我们实际上是在推动极限。使用实型字体,外观和感觉也会更干净。



