重庆熊猫 Loading

C#教程 - 其他(Other)

更新记录
转载请注明出处:
2022年9月25日 发布。
2022年9月10日 从笔记迁移到博客。

== 和 Equals()区别

如果是引用类型,==运算符比较的是引用的对象是否指向同一个内存区域。 而Equals() 方法检查的是值是否相等。

Convert.ToString()和ToString()区别

Convert.ToString()和ToString()的区别是前者可以处理Null值,后者不可以。

获取控制台应用命令行参数

方法一:使用Main方法的参数

static void Main(string[] args)
{
    foreach (string arg in args)
    {
        Console.WriteLine(arg);
    }
    
    Console.ReadKey();
}

注意:这种方法获得的参数不包含程序名

方法二:使用Environment对象

static void Main(string[] args)
{
    string[] userInputArgs = Environment.GetCommandLineArgs();
    foreach (string arg in userInputArgs)
    {
        Console.WriteLine(arg);
    }
    
    Console.ReadKey();
}

获取控制台输入字符

static void Main(string[] args)
{
    string userInputLine = Console.ReadLine();
    Console.WriteLine(userInputLine);
    
    Console.ReadKey();
}

如何减少unbox和boxing

方法一:定义类型的时候,使用泛型方法、或者泛型类型

方法二:定义重载方法

参考:

https://msdn.microsoft.com/en-us/library/system.object.aspx

中的Remark

标准相等处理(Standard Equality Protocols)

说明

默认情况下

值类型使用对值进行比较来确定相等

引用类型使用对引用进行比较来确定相等

可以Override默认的相等来实现自定义的相等比较

自定义相等比较的方法:

​ The == and != operators

The virtual Equals method in object

The IEquatable interface

标准Override相等的方法:

Override GetHashCode() and Equals()

(Optionally) overload != and ==

(Optionally) implement IEquatable

实例:结构标准Override

public struct Area : IEquatable <Area>
{
    public readonly int Measure1;
    public readonly int Measure2;
    public Area (int m1, int m2)
    {
        Measure1 = Math.Min (m1, m2);
        Measure2 = Math.Max (m1, m2);
    }
    public override bool Equals (object other)
    {
        if (!(other is Area)) return false;
        return Equals ((Area) other); // Calls method below
    }
    public bool Equals (Area other) // Implements IEquatable<Area>
            => Measure1 == other.Measure1 && Measure2 == other.Measure2;
    public override int GetHashCode()
            => HashCode.Combine (Measure1, Measure2);
    public static bool operator == (Area a1, Area a2) => a1.Equals (a2);
    public static bool operator != (Area a1, Area a2) => !a1.Equals (a2);
}

相等重写最佳实践

重写equality operators (Equals(), ==, and !=)

重写GetHashCode() on value types if equality is meaningful.

实现IEquatable接口

Equals比较

使用Equals比较如果参数为Null,会抛出NullReferenceException异常

可以使用下面这种Override的方式进行重写:

public static bool AreEqual (object obj1, object obj2)
{
 if (obj1 == null) return obj2 == null;
 return obj1.Equals (obj2);
}

实例:注意==和Equal的差异

double x = double.NaN;
Console.WriteLine (x == x); // False
Console.WriteLine (x.Equals (x)); // True

实例:注意==和Equal的差异

var sb1 = new StringBuilder ("foo");
var sb2 = new StringBuilder ("foo");
Console.WriteLine (sb1 == sb2); // False (referential equality)
Console.WriteLine (sb1.Equals (sb2)); // True (value equality)

object.Equals静态方法

public static bool Equals (object objA, object objB)

实例:

object x = 3, y = 3;
Console.WriteLine (object.Equals (x, y)); // True
x = null;
Console.WriteLine (object.Equals (x, y)); // False
y = null;
Console.WriteLine (object.Equals (x, y)); // True

object.ReferenceEquals静态方法

实例:

Widget w1 = new Widget();
Widget w2 = new Widget();
Console.WriteLine (object.ReferenceEquals (w1, w2)); // False
IEquatable接口(IEquatable interface)
public interface IEquatable<T>
{
 bool Equals (T other);
}

实例:

class Test<T> where T : IEquatable<T>
{
 public bool IsEqual (T a, T b)
 {
 return a.Equals (b); // No boxing with generic T
 }
}

标准比较处理(Standard Order Comparison)

标准比较重写

使用IComparable interfaces (IComparable and IComparable)

重写 > and < operators

IComparable接口

大部分的基础类型都实现了IComparable接口

IComparable通常用于排序比较、集合中

具体的接口定义如下:

public interface IComparable
{ 
    int CompareTo(object other); 
}
public interface IComparable<in T> 
{ 
    int CompareTo(T other); 
}

实例:string类型已经预定义了IComparable接口

string[] colors = { "Green", "Red", "Blue" };
Array.Sort (colors);
foreach (string c in colors) Console.Write (c + " "); // Blue Green Red

实例:结构重写IComparable接口和IEqualable接口

public struct Note : IComparable<Note>, IEquatable<Note>, IComparable
{
    int _semitonesFromA;
    public int SemitonesFromA { get { return _semitonesFromA; } }
    public Note (int semitonesFromA)
    {
        _semitonesFromA = semitonesFromA;
    }
    public int CompareTo (Note other) // Generic IComparable<T>
    {
        if (Equals (other)) return 0; // Fail-safe check
        return _semitonesFromA.CompareTo (other._semitonesFromA);
    }
    int IComparable.CompareTo (object other) // Nongeneric IComparable
    {
        if (!(other is Note))
        throw new InvalidOperationException ("CompareTo: Not a note");
        return CompareTo ((Note) other);
    }
    public static bool operator < (Note n1, Note n2)
        => n1.CompareTo (n2) < 0;
    public static bool operator > (Note n1, Note n2)
        => n1.CompareTo (n2) > 0;
    public bool Equals (Note other) // for IEquatable<Note>
        => _semitonesFromA == other._semitonesFromA;
    public override bool Equals (object other)
    {
        if (!(other is Note)) return false;
        return Equals ((Note) other);
    }
    public override int GetHashCode() => _semitonesFromA.GetHashCode();
    public static bool operator == (Note n1, Note n2) => n1.Equals (n2);
    public static bool operator != (Note n1, Note n2) => !(n1 == n2);
}

重写 > and < operators

大部分基础类型都重写了>和<运算符

实例:

bool after2010 = DateTime.Now > new DateTime (2010, 1, 1);

类型不同但成员相同的比较

实例:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
Console.WriteLine (a1 == a2); // False
Console.WriteLine (a1.Equals (a2)); // False
IStructuralEquatable se1 = a1;
Console.WriteLine (se1.Equals (a2,
StructuralComparisons.StructuralEqualityComparer)); // True
posted @ 2022-09-25 13:43  重庆熊猫  阅读(154)  评论(0编辑  收藏  举报