简体   繁体   English

C#警告:已分配变量但从未使用过

[英]C# Warning: Variable is assigned but never used

I see this warning in a lot of places in my code because of a specific paradigm I keep using throughout. 由于我一直使用特定的范例,因此我在代码中的很多地方都看到了这个警告。 Within objectA, I create objectB and objectB does a lot of it's own work that is necessary, but not referenced anywhere else. 在objectA内,我创建了objectB,而objectB做了很多必要的工作,但没有其他地方引用。

The only answers to this question I see are: 我看到的这个问题的唯一答案是:

  • Suppress the warning 禁止警告
  • You are doing something wrong. 您做错了。

Example of what I'm doing in lots of places. 我在很多地方正在做的事的例子。

class A {
    B b;
    public A() { 
        b = new B(); 
    }
}

class B {
    public B() {
        Updater.RegisterForSuperImportantUpdates(this);
    }

    public void Update() { 
        // super important stuff happening here 
        ....
    }
}

Does this seem like a valid design or is there an off putting odor here. 这看起来像是有效的设计,还是这里散发出臭味? Suppressing the warning is going to be annoying because this pattern is going to be used frequently. 取消警告将很烦人,因为这种模式将被频繁使用。

Why do you want to keep a reference to b(B) if you are not using it after? 如果以后不使用b(B),为什么要保留它的引用? Can't you just new it without keeping it referenced? 您是否可以不参考而只是更新它?

As it seems to be referenced by a third class not mentioned here ( Updater ), it should not be GCeed. 由于似乎由此处未提及的第三类( Updater )引用,因此不应对其进行GCeed。

根据干净代码的原则,这是一个有效的警告,您应将代码保持整洁,以使将要修复代码的第二个人不要与代码中使用的未使用变量混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM