简体   繁体   中英

Using .NET analyzer rule CA1001 for components of a framework which does not use IDisposable

I have a Unity project with Roslyn analyzers enabled, one of them is CA1001: "Types that own disposable fields should be disposable" ( https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1001 ).

This comes in handy for classes which are created and destroyed manually, to see if they properly dispose all of their fields. However in a lot of cases due to the viral nature of IDisposable the topmost objects creating these will be components, MonoBehaviour classes in the case of Unity. To satisfy the rule one would add IDisposable to the MonoBehaviour and implement the dispose pattern properly, however that does not add much value to the class, as being component of a framework which does not rely on IDisposable it will never be called.

What would seem to be the best in this case is to alter the rule somehow to check if IDisposable fields have been disposed in the OnDestroy method. Is there a way to change rule CA1001 to work like this for MonoBehaviour subclasses? Or is there any other analyzer which can do this? If not then at least could the rule be disabled for subclasses of a specific type? (The best I could do so far is to suppress the rule for files named "*Component.cs" but that's far from best.)

My question is targeted toward Unity but it actually applies to any framework not relying on the IDisposable interface.

Edit:

Example code:

public class Resource : IDisposable
{
    public void Dispose()
    {
        Debug.Log("Resource disposed");
    }
}

public class ExampleComponent : MonoBehaviour
{
    private Resource resource;

    private void Start()
    {
        resource = new Resource();
    }

    private void OnDestroy()
    {
        resource.Dispose();
    }
}

In this case resource is properly disposed in the conventional OnDestroy method but CA1001 is still triggered.

I think you could ignore the rule for any type derived from UnityEngine.MonoBehaviour via Exclude specific types and their derived types (in the very same link you posted)

add the following key-value pair to an .editorconfig file in your project

something like

dotnet_code_quality.CA1001.excluded_type_names_with_derived_types = T:UnityEngine.MonoBehaviour

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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