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

あなたのDBLookupフィールドはである必要がありDictionary<string, MyDel>ます。そうすれば、値を取得するときに、返されるタイプはでMyDelはなく、になりobjectます。

out引数として渡す参照のタイプはパラメーターのタイプと正確に一致する必要があるため、エラーが発生します。out引数はタイプでMyDelあり、パラメータTryGetValueobject(ディクショナリの値のタイプであるため)であるため、エラーが発生します。上記の変更を行うと、引数のタイプがパラメータのタイプと一致し、エラーメッセージが表示されなくなります。

一般に、値を保持するディクショナリを宣言していることobjectに気付いた場合は、実際に何を格納するかを検討し、代わりに別のタイプを使用できるかどうかを確認してください。

于 2011-08-16T19:58:44.257 に答える
1

辞書を次のように定義します

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

それに応じて残りのコードを変更します...

于 2011-08-16T20:00:08.757 に答える
1

Your dictionary stores objects, not instances of MyDel. Because it would be entirely possible for you to do this:

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

The compiler won't let you pass a variable as out that can't hold any value that the dictionary can hold. You have two choices:

  • Change your dictionary to a Dictionary<string, MyDel> (this is the best option if the dictionary really only stores instances of MyDel with a string key)
  • Use an intermediate variable for retrieval

Like so:

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

Or if you need an object type like a value in your dictionary in TryGetValue first use an object to get a value and after cast it delegate type you are sure be retrieved.

于 2011-08-16T20:02:59.850 に答える