我经常发现自己需要创建一个类作为某些数据的容器。它只被短暂使用,但我仍然必须创建类。像这样:
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.
}
是否有更好的方法来为一堆不同的类型创建一个临时容器,或者每次我需要一个临时对象来将事物组合在一起时是否需要定义类?
提前致谢。
最佳答案
Tuple可能是您正在寻找的解决方案。
public void DoSomething()
{
var temp = Tuple.Create("test", "blah blah blah", DateTime.Now);
DoSomethingElse(temp);
}
public void DoSomethingElse(Tuple<string, string, DateTime> data)
{
// ...
}
关于c# - 如何在不显式创建类的情况下创建要传递的临时对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7018884/