【问题标题】:Why does Rider suggests me to use deconstruction?为什么 Rider 建议我使用解构?
【发布时间】:2021-05-30 09:18:31
【问题描述】:

我正在写这门课:

private class SameCellsComparer : EqualityComparer<Links> 
{
    public override bool Equals(Links t1, Links t2)
    {
        return t1 == null || t1.Equals(t2);
    }
    public override int GetHashCode(Links t)
    {
        // we suppose there will always be less than 100 000 000 items:
        return t.Item1.id + t.Item2.id * 100000000;
    }
}

但是 Rider 建议我在 GetHashCode(Links t) 上使用解构,如果我应用他的建议,我会得到:

private class SameCellsComparer : EqualityComparer<Links> 
{
    public override bool Equals(Links t1, Links t2)
    {
        return t1 == null || t1.Equals(t2);
    }
    public override int GetHashCode(Links t)
    {
        // we suppose there will always be less than 100 000 000 items:
        (Cell item1, Cell item2) = t;
        return item1.id + item2.id * 100000000;
    }
}

请不要说做坏事GetHashCode()原则,我只求转换成(Cell item1, Cell item2) = t:是不是更安全、更快、更干净?没看懂。

【问题讨论】:

  • 如果你看list of all inspections这个默认的严重级别是“提示”——最低级别是described as“这个严重级别的代码问题会引起你对特定代码细节的注意和/或建议改进方法”。

标签: c# rider


【解决方案1】:

这只是一个语法糖。 通过解构,您可以控制元组项的名称。

查看我创建的gist

对于这个C#代码:

using System;
public class C {
    public void M() {
        (string fff,String fff2) = C.Do();
        
        var l = C.Do();
    }
    
   public static (String a, String b) Do(){
       return ("aaa", "bvvvv");
   }
}

编译器是这样看的:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public class C
{
    public void M()
    {
        ValueTuple<string, string> valueTuple = Do();
        string item = valueTuple.Item1;
        string item2 = valueTuple.Item2;
        ValueTuple<string, string> valueTuple2 = Do();
    }

    [return: TupleElementNames(new string[] {
        "a",
        "b"
    })]
    public static ValueTuple<string, string> Do()
    {
        return new ValueTuple<string, string>("aaa", "bvvvv");
    }
}

注意这行:

  ValueTuple<string, string> valueTuple = Do();
        string item = valueTuple.Item1;
        string item2 = valueTuple.Item2;
        ValueTuple<string, string> valueTuple2 = Do();

代码大致相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2012-06-12
    • 2023-03-13
    相关资源
    最近更新 更多