开发者

Generics and Action Delegate

I have the following code :

public void generate()
{
  base.generateFoo(Method); // How can i indicate the type here?
}

public void Method<T>(T t , IDictionary<T, SomeObject> coll) : where T : ISomething
{
 // do something
}


class MyBase
{
  public void generateFoo<T>(Action<T, IDictionary<T, SomeObject>> Method) : where T : ISomething
  {
     Method.invoke(ObjectThatImplementsT, DictionaryWIthTKey);
  }
}

I m getting an error like cannot convert ObjectThatImplementsT to T.

Can i pass a generic 开发者_StackOverflow社区method as a paramter to another method?

What s the problem here?

Thanks.


You probably just need to specify the type:

public void generate()
{
   base.generateFoo<YourType>(Method);
}

That being said - the above code, as written, will not compile, since generateFoo is not a generic method nor in a generic class, so it's possible the above will not work. It's assuming that generateFoo is defined as a generic method (taking type T).


You could make generateFoo generic to T, with the same restrictions as Method. Your example actually won't compile otherwise, as T is unknown to MyBase (unless you actually have a class named T in a known namespace).


All of the above applies, lots of minor edits (why don't you compile your sample yourself so we can know what 'problems' are bogus and what is really your question?!)

Here is a compiling bit - note three variations of calling generateFoo:

using System.Collections.Generic;
using System;

namespace X 
{ 
    class Y : MyBase
    {
        public static void Main(string[]args) { }

        public void generate()
        {
            base.generateFoo<Something>(Method<Something>); // works
            base.generateFoo<Something>(Method); // works as well
            base.generateFoo(Method<Something>); // doesn't (cannot be inferred)
        }

        public void Method<T>(T t , IDictionary<T, SomeObject> coll) 
            where T : ISomething
        {
            // do something
        }

    }

    class MyBase
    {
        public void generateFoo<T>(Action<T, IDictionary<T, SomeObject>> Method) 
            where T : class, ISomething
        {
            Method.Invoke((T) null, new Dictionary<T,SomeObject>());
        }
    }
    internal interface ISomething {}
    internal class Something : ISomething {}
    internal class SomeObject {}
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜