方法参数中的简单初始化器

时间:2011-08-13 14:11:10

标签: c# fluent object-initializer

我建立了一个流畅的界面:

criador.Include("Idade", 21).Include("Idade", 21);

我可以这样做:

criador.Include({"Idade", 21},{"Idade", 21});

我尝试使用params关键字的用户方法:

public myType Include(params[] KeyValuePair<string,object> objs){
    //Some code
}

但我需要这样做:

criador.Include(new KeyValuePair<string, object>{"Idade", 21}, new KeyValuePair<string, object>{"Idade", 21});

关键是我不想在方法

上没有写“new”关键字

3 个答案:

答案 0 :(得分:1)

您可以使用隐式转换:

public class ConvertibleKeyValuePair
{
    public ConvertibleKeyValuePair(string key, int value)
    {
        _key = key;
        _value = value;
    }

    public static implicit operator ConvertibleKeyValuePair(string s)
    {
        string[] parts = s.Split(';');
        if (parts.Length != 2) {
            throw new ArgumentException("ConvertibleKeyValuePair can only convert string of the form \"key;value\".");
        }
        int value;
        if (!Int32.TryParse(parts[1], out value)) {
            throw new ArgumentException("ConvertibleKeyValuePair can only convert string of the form \"key;value\" where value represents an int.");
        }
        return new ConvertibleKeyValuePair(parts[0], value);
    }

    private string _key;
    public string Key { get { return _key; } }

    private int _value;
    public int Value { get { return _value; } }

}

//测试

private static ConvertibleKeyValuePair[] IncludeTest(
    params ConvertibleKeyValuePair[] items)
{
    return items;
}

private static void TestImplicitConversion()
{
    foreach (var item in IncludeTest("adam;1", "eva;2")) {
        Console.WriteLine("key = {0}, value = {1}", item.Key, item.Value);
    }
    Console.ReadKey();
}

答案 1 :(得分:0)

一种方法是使用Tuple s:

criador.Include(Tuple.Create("Idade", 21), Tuple.Create("Idade", 21));

或者您可以创建一个可以保存值的类型:

criador.Include(new StrIntDict{ {"Idade", 21}, {"Idade", 21} });

StrIntDict基本上是Dictionary<string, int>:它必须实现IEnumerable并拥有方法Add(string, int)。 (您可以直接使用Dictionary<string, int>,但我认为您的目标很简洁,这么长的名字对此没什么帮助。)

答案 2 :(得分:0)

另一种方法是写几个重载:每个额外的几个参数需要一个重载。 这似乎有点矫枉过正,但实际上可以使代码非常清晰。

public void Include(string k0, object v0) { ... }
public void Include(string k0, object v0, string k1, object v1) { ... }
public void Include(string k0, object v0, string k1, object v1, string k2, object v2) { ... }
public void Include(string k0, object v0, string k1, object v1, string k2, object v2, string k3, object v3) { ... }
public void Include(string k0, object v0, string k1, object v1, string k2, object v2, string k3, object v3, string k4, object v4) { ... }

每种方法都执行不同的操作。 不好的是,你有最多数量的固定参数。

好的,您可以针对每项功能优化呼叫,从而提高性能。

如果需要,您还可以使用此方法对基类或接口使用扩展方法。

相关问题