I'm trying to create a class that at runtime can be pointed to various data inputs. To do this I am trying to use delegates. I have a worker method that returns a string (in the actual implementation, there would be others to choose from). The return value of the delegate is then returned from a method exposed to the rest of the code.

private delegate string delMethod();
private static delMethod pntr_Method = new delMethod(OneDelegateMethod);

public static string ExposedMethod()
{
    return pntr_Method;
}
public static string OneDelegateMethod()
{
    return "This is a string";
}

I'm getting this error

Cannot implicitly convert type 'OB.DataBase.delMethod' to 'string'

I'm puzzled why I get this, when this method has worked for bools and IDataReaders.

有帮助吗?

解决方案

If you want to call the delegate and return the value, you have to use "()":

public static string ExposedMethod()
{
    return pntr_Method();
}

其他提示

You need to call the delegate in order for it to return a string value. Delegates are really just pointers to methods, and need to be called using parenthesis in order to execute the method they point to. Here is a fixed version of your code:

private delegate string delMethod();
private static delMethod pntr_Method = new delMethod(OneDelegateMethod);

public static string ExposedMethod()
{
    return pntr_Method();
}
public static string OneDelegateMethod()
{
    return "This is a string";
}

You have to invoke the target method:

public static string ExposedMethod()
{
  return pntr_Method();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top