分配的值未在任何执行路径中使用-C# [英] Value assigned is not used in any execution path - C#

查看:249
本文介绍了分配的值未在任何执行路径中使用-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Resharper显示此警告:当我编写以下代码时,在任何执行路径中均未使用分配的值":

Resharper is showing this warning: "value assigned is not used in any execution path" when I write the following code:

List<obj> testObj = new List<obj>();
testObj = testMethod();

此处testMethod()返回类型List<obj>.但是,当我直接实例化testMethod()而不实例化它时,我没有得到警告.

Here testMethod() returns type List<obj>. However when I directly assign the testMethod() without instantiating it, I don't get the warning.

List<obj> testObj = testMethod();

如果我缺少基础知识,请原谅我的无知,但我没有遵循编译器如何在不实例化的情况下为testObj分配内存.

Forgive me for my ignorance, if I am missing the basics but I'm not following how the compiler allocates memory for testObj without instantiating it.

其中一则帖子涉及类似的问题: C#此初始化程序真的多余吗? ?,但是对于testObj变量存储从testMethod接收到的值的位置,我没有找到任何答案.与原始数据类型不同,对象类型"仅在实例化之后才能存储值.如果我缺少某些东西,请告诉我.

One of the posts refers to similar question: C# Is this initialiser really redundant? but I don't find any answer to my question, as to where the testObj variable is storing the value it received from testMethod? Unlike primitive data types, 'object types' can store value only after they are instantiated. Please let me know, if I am missing something.

推荐答案

您将在第一行中创建List<object>的实例.然后,通过为testObj变量分配从方法testMethod返回的另一个值,可以将此对象扔掉.此new List<obj>()对象是多余的.您有效地创建了垃圾回收器必须在某些时候清理的垃圾.

You are creating an instance of a List<object> in the first line. And then you throw this object away by assigning the testObj variable another value returned from your method testMethod. This new List<obj>() object is redundant. You effectively creating garbage that Garbage Collector will have to clean at some point.

这就是ReSharper向您显示警告的原因.

That's why ReSharper showing you warning.

如果您可以在定义变量的同一行中用 actual 值初始化变量,则执行该操作.

If you can initialize variable with actual value right in the same line where the variable is defined then do it.

编辑(假设我们正在谈论问题中提供的情况):

EDIT (assuming we are talking about situation provided in the question):

  1. new运算符本身不处理变量.它在中创建一个新对象(用于引用类型).
  2. =运算符将分配给堆栈中的变量.在这种情况下, value 是对堆中对象的引用.
  3. 将值分配给从方法或对象构造函数返回的变量之间没有区别.对象构造函数实际上也是一种方法.
  4. 在可以为变量赋值之前,无需对其进行初始化.实际上,按定义初始化是将初始值分配给变量.
  1. new operator does not deal with variable itself. It creates a new object in the heap (for reference types).
  2. = operator assigns a value to a variable in the stack. In this case value is a reference to an object in the heap.
  3. There is no difference between assigning a value to a variable returned from a method or an object constructor. Object constructor is actually a method too.
  4. Variable don't need to be initialized before it's possible to assign a value to it. Actually initialization by definition is an assignment of initial value to a variable.

这篇关于分配的值未在任何执行路径中使用-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆