开发者

How to store function OR string as value in dictionary (C#)

开发者 https://www.devze.com 2023-01-28 06:39 出处:网络
I need need to create dictionary whose key is string and values is either (delegate function OR string).

I need need to create dictionary whose key is string and values is either (delegate function OR string).

Because, I want to implement call back me开发者_JAVA百科chanism, wherein sometimes I need function for more processing which returns string and sometimes just need to fixed string.

Is there any way to do that in C#?

Thank you


I think the easiest way is to create a Dictionary<string, Func<string>>. This can obviously hold the call back case. For the non-call back case you can create a trivial lambda to return the hard coded value.

private Dictionary<string, Func<string>> m_map;
public void AddValue(string key, string value) {
  m_map[key] = () => value;
}
public void AddValue(string key, Func<string> value) {
  m_map[key] = value;
}


In the case where you need to have a fixed string you can instead create a function which returns a fixed string. Then in both cases you only need to deal with functions which return strings.


A Dictionary<string, object> would do the trick, you'll just need to cast the result to string or Func<string>.


Declare the value of the dictionary as object.


Create an object with a string property. That object has the smarts to return the string or call your function to get the string based on its constructor. Then put these in your dictionary Dictionary

public class MyCoolClass
{
    public MyCoolClass(Func<string> getString)
    {
        m_getString = getString;
    }
    public MyCoolClass(string s)
    {
        m_string = s;
    }
    public string GetString()
    {
        return m_string ?? getString();
    }
    private string m_string;
    private Func<string> m_getString;
}


An example that uses a Dictionary

static void Main()
{        
    var dic = new Dictionary<string, Func<string>>();

    dic.Add("A", () => "Hello World");  // Constant lambda
    dic.Add("B", ConstructString);      // Calculated
    dic.Add("C", delegate { return string.Empty; });    // Anonymous delegate
}

static string ConstructString()
{
    return DateTime.Now.ToString();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消