void something(){ var o =new{ Id =1, Name ="foo"}; var emptyListOfAnonymousType = CreateEmptyGenericList(o); }
会有用的。
你也可以考虑这样写:
1 2 3 4 5
void something(){ varString=string.Emtpy; var Integer =int.MinValue; var emptyListOfAnonymousType = CreateEmptyGenericList(new{ Id = Integer, Name =String}); }
var list =new[]{ new{
FirstField =default(string),
SecondField =default(int),
ThirdField =default(double) } }.ToList();
list.RemoveAt(0);
号
而不是这个:
1 2 3 4 5 6
var o =new{ Id =1, Name ="Foo"}; var o1 =new{ Id =2, Name ="Bar"};
List <var> list =new List<var>();
list.Add(o);
list.Add(o1);
。
你可以这样做:
1 2 3 4 5 6
var o =new{ Id =1, Name ="Foo"}; var o1 =new{ Id =2, Name ="Bar"};
List<object> list =new List<object>();
list.Add(o);
list.Add(o1);
但是,如果在另一个作用域中尝试执行类似的操作,则会出现编译时间错误,尽管它在运行时工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
private List<object> GetList() {
List<object> list =new List<object>(); var o =new{ Id =1, Name ="Foo"}; var o1 =new{ Id =2, Name ="Bar"};
list.Add(o);
list.Add(o1); return list; }
namespace ConsoleApplication1 { class Program { staticvoid Main(string[] args) {
Program p =new Program(); var anonymous = p.GetList(new[]{ new{ Id =1, Name ="Foo"}, new{ Id =2, Name ="Bar"} });
p.WriteList(anonymous); }
private List<T> GetList<T>(params T[] elements) { var a = TypeGenerator(elements); return a; }
var people=new List<Tuple<int, int, string>>(){ {1, 11,"Adam
<hr><P>根据这个答案,我想出了两种方法来完成这个任务:</P>[cc lang="csharp"] /// <summary>
/// Create a list of the given anonymous class. <paramref name="definition"/> isn't called, it is only used
/// for the needed type inference. This overload is for when you don't have an instance of the anon class
/// and don't want to make one to make the list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="definition"></param>
/// <returns></returns>
#pragma warning disable RECS0154 // Parameter is never used
public static List<T> CreateListOfAnonType<T>(Func<T> definition)
#pragma warning restore RECS0154 // Parameter is never used
{
return new List<T>();
}
/// <summary>
/// Create a list of the given anonymous class. <paramref name="definition"/> isn't added to the list, it is
/// only used for the needed type inference. This overload is for when you do have an instance of the anon
/// class and don't want the compiler to waste time making a temp class to define the type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="definition"></param>
/// <returns></returns>
#pragma warning disable RECS0154 // Parameter is never used
public static List<T> CreateListOfAnonType<T>(T definition)
#pragma warning restore RECS0154 // Parameter is never used
{
return new List<T>();
}
号
你可以使用以下方法
1 2 3 4
var emptyList = CreateListOfAnonType(()=>new{ Id =default(int), Name =default(string)}); //or var existingAnonInstance =new{ Id =59, Name ="Joe"}; var otherEmptyList = CreateListOfAnonType(existingAnonInstance);