【发布时间】:2021-02-19 08:39:13
【问题描述】:
我来自 Java 和 C++ 背景。但是,我目前正在做一个 C# 应用程序,但有一件事让我感到困惑。
在 Java 中,当我导入一个包时,这意味着我可以访问放置在该包中的类。比如这里我从包java.util中导入了ArrayList类。
import java.util.ArrayList;
class ArrayListUtilization {
public static void main(String[] args) {
ArrayList<Integer> myList = new ArrayList<>(3);
myList.add(3);
myList.add(2);
myList.add(1);
System.out.println(myList);
}
}
最近我在我的 c-sharp 应用程序中遇到了一个问题,我问了here。在我看来,有趣的是,当我添加了以下 sn-p 代码时:
var accountDbContext = services.GetRequiredService<AccountDbContext>();
accountDbContext.Database.EnsureCreated();
var accountDbCreator = accountDbContext.GetService<IRelationalDatabaseCreator>();
accountDbCreator.CreateTables();
我看到如下错误:
错误 CS1929 'AccountDbContext' 不包含 'GetService' 和最好的扩展方法重载 'ServiceProviderServiceExtensions.GetService(IServiceProvider)' 需要“IServiceProvider”类型的接收器
从错误文本中,我了解到accountDbContext 对象没有GetService 功能。但是当我按下show potential fixes 时,它会建议我添加一个using 语句。
这是真正的解决方案。但是,我的问题是这个using 语句对我的对象有什么影响?该对象是其类的实例。如何在我的对象上添加using 语句并为其添加函数?
【问题讨论】:
-
使用就像在 Java 中导入,我来自 Java 背景,我切换到 C# 以及一些需要导入的方法(你可能已经知道),或者你可以这样做:Microsoft.EntitiyFrameworkSomethingSomething。 Infra.Method.Function (很长),这是在 C# 中做某事的一种不安方式,也许你的班级需要它?我不确定
-
也许你的班级需要它我不确定
-
那是什么关系呢?我可以访问我的对象。这种使用将消除缺少功能的错误。
-
@John 谢谢,我会跟进那个关键字。