简体   繁体   English

在.net 4中以匿名方式使用委托

[英]Using delegate in an anonyous method in.net 4

Been given task to upgrade some code from .net 2 written in VS2005 to .net 4 using VS2010. 获得的任务是使用VS2010将VS2005中编写的.net 2的某些代码升级到.net 4。 When trying to compile the code I'm getting the error: 尝试编译代码时出现错误:

Cannot convert anonymous method to delegate type 'AssignParameter' because the parameter types do not match the delegate parameter types 无法将匿名方法转换为委托类型'AssignParameter',因为参数类型与委托参数类型不匹配

The code in question the compile error is pointing at is: 编译错误所指向的代码有问题:

AssignParameter ap = delegate(Database db, DbCommand cmd)
{
  db.AddInParameter(cmd, _jobIDParameterString, DbType.Int32, jobid);
};

DatabaseHelper.LoadDataSet(ap);

So I tracked the code to the location that the delegate reference lives: 因此,我将代码跟踪到委托引用引用的位置:

public delegate void AssignParameter(Database db, DbCommand cmd);
public class DatabaseHelper
{
    private static Database msSqlDb;

    public static DataSet LoadDataSet(AssignParameter parameter)
    {
         ...
         DbCommand command = ...
         // Assign parameter
         if (parameter != null)
         {
             parameter(msSqlDb, command);
         }
         ...
    }
}

So I've read that delegate keyword can't be used in that way 所以我读到委托关键字不能以这种方式使用

http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/ http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/

But still struggling to understand how to fix my issue. 但仍在努力了解如何解决我的问题。

I tried 我试过了

  • casting the delegate 选派代表
  • creating a new AssignParameter call but the problem there is that I don't have either Database or DbCommand objects available 创建一个新的AssignParameter调用,但问题是我没有数据库或DbCommand对象可用

Do you have any suggestions on how to fix this problem? 您对如何解决此问题有任何建议吗?

One of the types of the parameters you're using in your method refers to a different type than the delegate defines, as the error said. 如错误所述,您在方法中使用的参数类型之一是与委托定义的类型不同。

This means that either, unlike the code that you posted, your actual code uses different types in one of those places, or you have multiple types for one/both of those parameters with the same name in different namespaces. 这意味着,与您发布的代码不同,您的实际代码在这些位置之一中使用了不同类型,或者对于具有相同名称在不同名称空间中的两个参数,您拥有多种类型。

public class Database
{
}

public class DbCommand
{
}

public delegate void AssignParameter(Database db, DbCommand cmd);

…

AssignParameter ap = delegate(Database db, DbCommand cmd)
{
};

This code compiles fine for me, so there must be something else going on. 这段代码对我来说编译很好,因此必须进行其他操作。 Are you sure that the two sets of Database and DbCommand refer to the same types? 您确定两组DatabaseDbCommand引用相同的类型吗? And that the code inside the delegate is itself valid? 而且委托中的代码本身就是有效的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM