c# - 如何在不显式创建类的情况下创建要传递的临时对象?

标签 c# .net oop object anonymous-types

我经常发现自己需要创建一个类作为某些数据的容器。它只被短暂使用,但我仍然必须创建类。像这样:

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/

相关文章:

python - 与 super() 调用有点困惑

c# - 如何找到所有图形卡? C#

.net - .net 4.5 升级后 System.Web.Http 丢失

c# - 在没有数据重复的情况下转换/实例化/转换为子类/父类(super class)

delphi - 当一个类已经扩展了一个类和一个接口(interface)时如何继承另一个类

c# - 移动和旋转 map 有问题吗?

c# - gridview 以编程方式编辑模式

c# - SpreadsheetLight 处理多个工作表

c# - 统一,C# |如何在方法之间设置等待时间?

c# - 面向初学者的 Spec Explorer