相关疑难解决方法(0)

多重继承的确切问题是什么?

我可以看到人们一直在询问是否应该在下一版本的C#或Java中包含多重继承.有幸拥有这种能力的C++人说,这就像给某人一条绳子最终自我吊死.

多重继承有什么问题?有没有具体的样品?

oop language-theory multiple-inheritance

115
推荐指数
7
解决办法
7万
查看次数

C# 类可以从其自己的实现中调用接口的默认接口方法吗?

如果我有一个像这样的默认接口方法:

public interface IGreeter
{
    void SayHello(string name) => System.Console.WriteLine($"Hello {name}!");
}
Run Code Online (Sandbox Code Playgroud)

我可以让我的具体实现调用该默认方法吗?

public class HappyGreeter : IGreeter
{
    public void SayHello(string name)
    {
        // what can I put here to call the default method?
        System.Console.WriteLine("I hope you're doing great!!");
    }
}
Run Code Online (Sandbox Code Playgroud)

所以调用:

var greeter = new HappyGreeter() as IGreeter;
greeter.SayHello("Pippy");
Run Code Online (Sandbox Code Playgroud)

结果如下:

// Hello Pippy!
// I hope you're doing great!!
Run Code Online (Sandbox Code Playgroud)

事实上,从实现类中调用 C# 接口默认方法表明我可以调用我的类未实现的方法,但正如预期的那样,添加对((IGreeter)this).SayHello(name);内部的调用HappyGreeter.SaysHello会导致堆栈溢出。

c# c#-8.0 default-interface-member

13
推荐指数
1
解决办法
1806
查看次数

为什么我的 C# 默认接口实现在具体类定义中未被识别?

我在 Visual Studio 2019 中有一个 .Net 6.0 应用程序。我正在尝试让默认接口实现正常工作。由于某种原因,它似乎无法识别类定义中的默认实现。

这是一个示例代码片段:

public interface IFooBar
{
    protected bool BoolProperty { get; set; }
    protected Guid StringProperty { get; set; }
    
    protected void SampleMethod1(string param)
    {
    }
    
    protected void SampleMethod2()
    {
    }
}

public class FooBase
{
}

public class Foo : FooBase, IFooBar
{

    protected bool IFooBar.BoolProperty { get; set; }
    protected Guid IFooBar.StringProperty { get; set; }
    
    protected SomeMethod()
    {
        SampleMethod1("Test String");
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我的 Visual Studio 2019 项目文件的片段:

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework> …
Run Code Online (Sandbox Code Playgroud)

c# .net-core default-interface-member

6
推荐指数
1
解决办法
2077
查看次数

C#如何从派生类调用接口方法

我有一个实现接口的类IPerson。我想从我的类中调用接口中实现的方法,但出现此错误:CS0103 当前上下文中不存在名称“SayMyName” 如何从派生类调用接口中实现的方法?

public interface IPerson
{
    string SayMyName()
    {
        return "MyName";
    }
}

public class Person : IPerson
{
    public void Method()
    {
        SayMyName();//ERROR CS0103 The name 'SayMyName' does not exist in the current context
    }
}
Run Code Online (Sandbox Code Playgroud)

c#

0
推荐指数
1
解决办法
64
查看次数