Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/184.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 基类方法无法从父类外部访问?_C#_.net - Fatal编程技术网

C# 基类方法无法从父类外部访问?

C# 基类方法无法从父类外部访问?,c#,.net,C#,.net,我想编写一个依赖项提供程序来注册我的依赖项。我继承了ServiceCollection类,这意味着我应该获得该类中的所有方法,对吗?看来是错的 你可以看到,我继承了它,使用this.关键字注册它,但是如果没有这个关键字,它就会出错 public class DependencyProvider : ServiceCollection, IDependencyProvider { public DependencyProvider() : base() { Regi

我想编写一个依赖项提供程序来注册我的依赖项。我继承了ServiceCollection类,这意味着我应该获得该类中的所有方法,对吗?看来是错的

你可以看到,我继承了它,使用
this.
关键字注册它,但是如果没有这个关键字,它就会出错

public class DependencyProvider : ServiceCollection, IDependencyProvider
{
    public DependencyProvider() : base()
    {
        Register();
    }

    public void Register()
    {
        this.AddSingleton<ICoreContext, CoreContext>();
    }
}
就像我回答的那样,
AddSingleton
IServiceCollection
上的一个扩展方法。这意味着,如果要在
DependencyProvider
中使用它,则需要使用
this.AddSingleton
或直接引用方法
ServiceCollectionServiceExtensions.AddSingleton

在没有这个的情况下调用AddSingleton。添加此时抛出一个错误,表示找不到方法。它按预期工作。如果我需要在类的实例上访问它呢

那么,在这种情况下,您只需按照预期使用它:

var myProvider = new DependencyProvider();
myProvider.AddSingleton<ICoreContext, CoreContext>();
var myProvider=newdependencProvider();
myProvider.AddSingleton();

AddSingleton
必须是扩展方法,而不是来自
ServiceCollection
的方法。这是因为
AddSingleton
是扩展方法。它未在
servicecolection
中定义,您必须将
servicecolection
传递给它才能工作。基本上,这转化为
ServiceCollectionServiceExtensions.AddSingleton(这个)
是否有任何方法可以直接从
DependencyProvider
的基类访问这些方法,就像我尝试的那样?我以为我已经回答了你这个问题…?不,你只是使用扩展方法。扩展方法将处理从
servicecolection
继承的类。
var myProvider = new DependencyProvider();
myProvider.AddSingleton<ICoreContext, CoreContext>();