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

标签 c# compiler-warnings

是否可以将接口(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/

相关文章:

c# - UWP 应用程序在不处于 Debug模式时崩溃

C# 找到带有部分键字符串的 WebCache?

c++ - 为什么 G++ 不警告 Const 成员的未使用结果?

Java:为什么编译器会在这里提示?

visual-c++ - "getenv... function ... may be unsafe"- 真的吗?

c# - Razor 框架 - 后端还是前端?

c# - C# .net 核心中的 Path.GetDirectoryName

c# - 线程、进程和 Application.Exit()

objective-c - 为什么我必须选派代表?

c++ - std::accumulate 中的 double 到 int 转换警告