我经常发现自己需要创建一个类作为容器的一些数据.它只是简单地使用,但我仍然需要创建类.喜欢这个:
public class TempObject { public string LoggedInUsername { get; set; } public CustomObject SomeCustomObject { get; set; } public DateTime LastLoggedIn { get; set; } } public void DoSomething() { TempObject temp = new TempObject { LoggedInUsername = "test",SomeCustomObject = //blah blah blah,LastLoggedIn = DateTime.Now }; DoSomethingElse(temp); } public void DoSomethingElse(TempObject temp) { // etc... }
通常我的临时对象有更多的属性,这就是我想把它们分组在一起的原因.我希望有一个更简单的方法,如匿名类型.问题是,当我将其传递给另一种方法时,我不知道该接受什么.这种类型是匿名的,那么我应该如何接受呢?
public void DoSomething() { var temp = new { LoggedInUsername = "test",SomeCustomObject = //blah blah,LastLoggedIn = DateTime.Now }; // I have intellisense on the temp object as long as I'm in the scope of this method. DoSomethingElse(temp); } public void DoSomethingElse(????) { // Can't get my anonymous type here. And even if I could I doubt I would have intellisense. }
有没有更好的方式为一堆不同类型创建一个临时容器,或者每次需要临时对象来将事物分组在一起时,是否需要定义类?
提前致谢.