0

我正在尝试使用字典来引用委托,但是当我尝试检索委托指针时出现错误。对于更多上下文,我得到了一个用于在 C 结构中查找值的字符串。我已经编写了在 C 结构中获取/设置数据的方法,但现在我需要调用给定字符串的方法。如果您有更好的方法,请告诉我。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestCode
{
    public class tuboFillLinePresets
    {
        public IDictionary<string, object> DBLookup { get;  set; }
        public config_data Data;

        delegate float MyDel(int chan);

        public float ChanGain(int chan)
        {
            return Data.ChannelGain(chan);
        }

        public float MagCurr(int chan)
        {
           return Data.MagCurrent(chan);
        }

        public tuboFillLinePresets()
        {
            DBLookup = new Dictionary<string, object>();
            MyDel cg = new MyDel(ChanGain);
            MyDel mc = new MyDel(MagCurr);
            DBLookup.Add("HBGain", cg);
            DBLookup.Add("LBGain", cg);
            DBLookup.Add("MagCurrent", mc);
        }

        public LinePresets tuboGetLinePresets(LinePresets LinePresets)
        {
           foreach (var item in LinePresets.Parameters)
           {
               String s = item.Key;
               MyDel func;
               DBLookup.TryGetValue(s, out func);  // error here 
               LinePresets.Parameters[s] = func(3);
           }
           return LinePresets;
       }
   }
}
4

4 回答 4

6

Your DBLookup field should be a Dictionary<string, MyDel>. That way, when getting the value, the returned type will be a MyDel, rather than an object.

You get the error because the type of the reference that you pass as an out argument must match the type of the parameter exactly. Since the out argument is of type MyDel and the parameter on TryGetValue is object (since that's the type of the value in your dictionary) you get an error. Once you make the above change, the type of the argument will match the type of the parameter, and the error message will disappear.

In general, if you find yourself declaring a dictionary that holds object values, consider what you'll actually be storing, and see if you can use a different type instead.

于 2011-08-16T19:58:44.257 回答
1

将您的字典定义为

public IDictionary<string, MyDel> DBLookup { get;  set; }

并相应地更改其余代码...

于 2011-08-16T20:00:08.757 回答
1

您的字典存储objects,而不是MyDel. 因为您完全有可能这样做:

DBLookup.Add("foo", "HAH!");

编译器不会让你传递一个变量,因为out它不能保存字典可以保存的任何值。你有两个选择:

  • 将您的字典更改为(如果字典真的只存储带有字符串键的Dictionary<string, MyDel>实例,这是最好的选择)MyDel
  • 使用中间变量进行检索

像这样:

object value;

if(DBLookup.TryGetValue(s, out value) && value is MyDel)
{
    func = (MyDel)value;
    LingPresents.Parameters[s] = func(3)
}
于 2011-08-16T20:02:15.573 回答
0

或者,如果您需要一个对象类型,例如 TryGetValue 中字典中的值,首先使用一个对象来获取一个值,然后将其转换为委托类型,您肯定会被检索到。

于 2011-08-16T20:02:59.850 回答