【问题标题】:C# Array of out params [duplicate]C#输出参数数组[重复]
【发布时间】:2021-10-01 05:12:23
【问题描述】:

我试图降低自定义 ORM 的复杂性,因此我正在尝试做这样的事情:

我的问题是我需要实现一个输出参数 Model[] 变量

类似的,

public bool GetEntities(params out Model[] models)

public bool GetEntities(out params Model[] models)

但是看起来我的语法对编译器无效,您是否有想法解决问题以返回不确定数量的对象作为输出参数而不实现 IEnumerable,例如数组、列表、字典......运行时快一点?

follow 块清楚地让您看到问题。

public class Model
{
}

public class Entity1 : Model
{
}

public class Entity2 : Model
{
}

public class EntityN : Model
{
}

public class FooDBContext
{
    private IDictionary<string,object> rows;
    public void SetSQLRecord(IDictionary<string,object> row)
    { 
     // This function sets a local dictionary that will be used to perform the multicast.
    }
    
    public IEnumerable<IEnumerable<object>> HasNext()
    {
      // this returns the current row returned by the query
        yield return null;
    }
    
    public bool TryExecuteSQL(string SQL )
    {
        //execute
        return true;
    }
    
    public void SetValues(params Model[] models)
    {
        
    }
    
    public bool GetEntities(params out Model[] models)
    {
    
    }
}

public class Program
{
    public static void Main()
    {
        var a = new FooDBContext();
        string SQL = "Select Entity1.* , Entity1.* , Entity2.* , EntityN.* , Entity2.* FROM Entity1,  Entity1,  Entity2,  EntityN,  Entity2 where (expression)";
        a.TryExecuteSQL(SQL);
        foreach(var row in a.HasNext())
        {
            a.GetEntities(out Entity1 e1_1,  out Entity1  e1_2,  out Entity2  e2_1,  out EntityN en_1 , out Entity2 e2_2 );
            a.GetEntities(out e1_1,  out e1_2);

        }
    }
}

【问题讨论】:

  • 据我所知,我认为您无法做到这一点。但是,您可以使用没有 out 的数组对象。 stackoverflow.com/questions/1912326/….
  • I need to implement an out params Model[] variable 你为什么认为你需要这样做?
  • 就像你可以使用参数 string[] args 来支持这个 a = Method(a,b,c,...,z) 我需要一个未确定的输出参数列表
  • 我不喜欢返回数组的实例,否则指向多个实例以直接将它们用作变量。
  • 如果您真的担心性能,您可能不应该使用IDictionary(而是使用DictionaryConcurrentDictionary)。

标签: c# parameters out


【解决方案1】:

我认为不可能做你想做的事。而是向参数添加一个集合并将其设置为输出参数。我建议这样做:

public bool GetEntities(out IList<Model[]> outputModel, params Model[] models)
{
   //method logic here
   //some assignment to argument outputModel
   // eg. outputModel.Add(//)
   // return true or false
}

【讨论】:

  • 这是一种解决方法,但我无法执行一些类似这样的操作:方法(out ClassA variable a , out ClassA variable b ,) 在同一指令中实例化它们
  • 如您所见:GetEntities(out Entity1 e1_1, out Entity1 e1_2, out Entity2 e2_1, out EntityN en_1, out Entity2 e2_2);您正在实例化将方法内部实例化的变量,
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 2013-06-24
  • 2011-04-11
相关资源
最近更新 更多