为什么我的扩展方法不起作用?

时间:2018-03-10 01:43:45

标签: c# .net entity-framework

我有一个扩展方法

public static class DbMigratorExtensions
{
    public static IEnumerable<string> DoCoolStuff(this DbMigrator dbMigrator, string[] first, string[] second)
    {
        // ... 
    }
}

我试图像

一样使用它
DbMigrator.DoCoolStuff

但是我得到了

'DbMigrator' does not contain a definition for ...

我已经按照

上的所有要点进行了操作

Why is my Extension Method not showing up in my test class?

另外我会注意到VS识别

DbMigratorExtensions.DoCoolStuff

所以我不确定为什么它不作为一种扩展方法。

2 个答案:

答案 0 :(得分:5)

扩展方法适用于对象实例,而不适用于类型。

所以你需要改变

DbMigrator.DoCoolStuff(...);

var migrator = new DbMigrator();
var stringList = migrator.DoCoolStuff(...);

如果DoCoolStuff()需要一个实例,则它不应该是扩展方法。

答案 1 :(得分:1)

如果您想要的是静态扩展方法,C#目前不支持此功能。您只能制作非静态扩展方法。这可能会在某些时候发生变化。

相关问题