gpt4 book ai didi

c# - 抽象类的不可空方法的可空实现

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:37 24 4
gpt4 key购买 nike

我有三个类(class)。称为 A 的接口(interface),以及实现 A 的 B 和 C。B 也有 C 的实例。A 的方法不能为 null。但是,C 可能会不时返回 null。 B 类检查 C 实例的方法,如果 C 的返回值为空,它将返回自身值(来自 B 的值)。

public abstract class A
{
bool abstract method1();
bool abstract method2();
}

public class B:A
{
public C c;
override bool method1()
{
//if c.method1 is not null return c.method1() otherwise do some other functionality
}
}

public class C:A
{
?
}

由于某些性能问题,我不想抛出异常。由于无法将覆盖类的类型更改为可为空,我该如何实现 C 类?

最佳答案

根据所述的严格要求,我设法想出了一种愚蠢的解决方案,但是哦,好吧 - 这有点..

void Main()
{
var a = new AProxy(new C(), new B());
for (int i = 0; i < 15; i++)
{
a.method1();
a.method2();
}
}
public abstract class A
{
public abstract bool method1();
public abstract bool method2();
}
public class AProxy : A
{
readonly A primary;
readonly A secondary;
public AProxy(A primary, A secondary)
{
this.primary = primary;
this.secondary = secondary;
if(primary is IReturnsNulls)
((IReturnsNulls)primary).LastResultNull += (s, e) =>
useSecondary = true;
}
private bool useSecondary;
private bool UseSecondary
{
get
{
if(useSecondary == true)
{
useSecondary = false;
return true;
}
return useSecondary;
}
}
public override bool method1()
{
var result = primary.method1();
return UseSecondary ? secondary.method1() : result;
}
public override bool method2()
{
var result = primary.method2();
return UseSecondary ? secondary.method2() : result;
}
}
public class B : A
{
public override bool method1()
{
Console.WriteLine ("B, method1 (secondary)");
return true;
}
public override bool method2()
{
Console.WriteLine ("B, method2 (secondary)");
return true;
}
}
public interface IReturnsNulls
{
event EventHandler LastResultNull;
}
public class C : A, IReturnsNulls
{
static Random random = new Random();
public override bool method1()
{
Console.WriteLine ("C, method1");
var result = (random.Next(5) == 1) ? (bool?)null : true;
if(result == null && LastResultNull != null)
LastResultNull(this, EventArgs.Empty);
return result ?? false;
}
public override bool method2()
{
Console.WriteLine ("C, method2");
var result = (random.Next(5) == 1) ? (bool?)null : true;
if(result == null && LastResultNull != null)
LastResultNull(this, EventArgs.Empty);
return result ?? false;
}
public event EventHandler LastResultNull;
}

输出:

C, method1
B, method1 (secondary)
C, method2
C, method1
C, method2
B, method2 (secondary)
C, method1
C, method2
C, method1
C, method2
C, method1
C, method2
C, method1
C, method2
C, method1
C, method2
C, method1
C, method2
C, method1
B, method1 (secondary)
C, method2
C, method1
C, method2
C, method1
C, method2
B, method2 (secondary)
C, method1
C, method2
C, method1
C, method2
B, method2 (secondary)
C, method1
C, method2
C, method1
C, method2

关于c# - 抽象类的不可空方法的可空实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com