简体   繁体   English

C#-使用可为空的类型作为参数

[英]C# - Using nullable types as parameters

Can anyone tell me if it is a good idea to accept nullable parameters for a function and then setting the parameter to null after using it? 谁能告诉我接受函数的可为空的参数,然后在使用后将参数设置为null是否是一个好主意? Would this be a good programming practice to free up unused resources? 这是释放未使用资源的良好编程习惯吗? Ex: 例如:

public static bool SendEmail(MailAddressCollection? To, string Subject, string Body)
{
    // use the values stored in To, Subject, and Body to send the message.
    To = null;
}

No , it's not a good idea. ,这不是一个好主意。 What you're doing has no practical impact. 您所做的没有实际影响。 The only variable you're setting to null is a local one for the method. 您设置为null的唯一变量是方法的本地变量 That variable will go out of scope automatically anyway. 无论如何,该变量将自动超出范围。

On the contrary, if you got that object as an argument, it means that there's a reference to that object outside of the current method anyway and you're not affecting that reference. 相反,如果您将该对象作为参数,则意味着无论如何在当前方法之外都存在对该对象的引用,并且您不会影响该引用。 So you're not helping the GC at all by doing anything inside the method as it is. 因此,您根本无法通过在方法内部进行任何操作来完全帮助GC。 The only way to have any non-local effect in this regard would be to pass all your arguments as ref and thus be able to set the passed variables to null. 在这方面产生任何非局部影响的唯一方法是将所有参数作为ref传递,从而能够将传递的变量设置为null。 However, this would be absolutely horrible because every innocent looking method call could potentially ruin references that are assumed not-null later on. 但是,这将是绝对可怕的,因为每个无辜的方法调用都可能会破坏以后被假定为非空的引用。

Generally, what you should do in most applications is not think about it. 通常,在大多数应用程序中不应该考虑的事情。 The GC is a lot better at detecting the unused memory, because it can examine the stack for references and it has access to relevant metadata emitted by the JIT compiler that you don't get to see. GC可以更好地检测未使用的内存,因为它可以检查堆栈中的引用,并且可以访问您看不到的JIT编译器发出的相关元数据。

No, it's not. 不,这不对。 You've got a GC to take care of that for you. 您有一个GC可以为您解决这个问题。 You're not in an unmanaged language, you don't need to dispose resources (unless they're IDisposable , of course). 您不是使用非托管语言,也不需要处理资源(当然,除非它们是IDisposable的)。

No, this is a bad practice in managed environment such as .NET. 不,这在.NET等托管环境中是一种不良做法。 Garbage collector in .NET can automatically collect objects with no references and free memory from them. .NET中的垃圾收集器可以自动收集没有引用的对象,并从中释放可用内存。

But there are rare exceptions. 但也有罕见的例外。 You can manually set reference to null and explicitly call GC: 您可以手动将引用设置为null并显式调用GC:

public static void ForceGC(ref object obj) {        
    obj = null;
    GC.Collect();
}

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

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