gpt4 book ai didi

c# - 将接口(interface)或类的已实现 IEnumerable 声明为已过时

转载 作者:太空狗 更新时间:2023-10-30 00:49:28 24 4
gpt4 key购买 nike

是否可以将接口(interface)或类的派生或实现的 IEnumerable 部分声明为已过时,而类或接口(interface)的其余部分仍然是最新的?我该如何申报?

interface Foo : IEnumerable<Bar>{

int SomethingNonObsolete{
get;
}

}

在上面的例子中,我希望使用已实现的 IEnumerable 的迭代器会导致编译器过时警告,而使用接口(interface)本身或使用 SomethingNonObsolete-Property 会不会导致这样的警告。

以下代码应该导致编译器过时的警告

foreach(var bar in myFooImplementingInstance){

以下代码不应导致编译器过时警告

myFooImplementingInstance.SomethingNonObsolete.ToString()

更新
因为有很多答案,但每个答案都只关注问题的一部分,这里做一个总结和最后的声明:

最后,由于 LINQ,技术上是不可能的。

如果无论如何都要使用它,正如 Panda 在他的回答中所展示的那样,对于类来说很容易做到。声明枚举器已过时,您可以罚款。

[Obsolete]
IEnumerator<Bar> GetEnumerator()
[Obsolete]
IEnumerator IEnumerable.GetEnumerator()

对于接口(interface),可以用类似的方式完成,正如 Bozhidar 在评论中所说的那样。使用 new 关键字声明枚举器并将其标记为过时。

[Obsolete]
new IEnumerator<ITabularDataRow> GetEnumerator();

但是,虽然这两个版本通常都可以执行它们应该执行的操作,但在使用 LINQ 时它们都会出错。因此,答案似乎是不可能以全面的方式进行,而且在大多数情况下这是好的(参见 MDeSchaepmeester 的回答和评论)。

最佳答案

在实现您的接口(interface)时,在 GetEnumerator 方法上添加 Obsolete 属性,如下所示会导致您的期望:

public class MyClass : Foo
{
public int SomethingNonObsolete
{
get
{
throw new NotImplementedException();
}
}

[Obsolete]
public IEnumerator<Bar> GetEnumerator()
{
throw new NotImplementedException();
}

[Obsolete]
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}

结果:

var c = new MyClass();

// Flagged as obsolete
foreach (var blah in c)
{

}

// Not flagged as obsolete
var s = c.SomethingNonObsolete;

关于c# - 将接口(interface)或类的已实现 IEnumerable 声明为已过时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37834131/

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