广西城乡和住房建设厅网站,网站数据库出问题,小程序源码怎么用,如何把做的网站与域名连接不上C#中的Object类是所有类的基类#xff0c;它定义了一些通用的方法和属性#xff0c;可以在任何对象上使用。以下是Object类中常用的方法和属性的使用#xff1a; 1.ToString()#xff1a;将对象转换为字符串表示形式。
string str obj.ToString();2.Equals()#xff1a;…C#中的Object类是所有类的基类它定义了一些通用的方法和属性可以在任何对象上使用。以下是Object类中常用的方法和属性的使用 1.ToString()将对象转换为字符串表示形式。
string str obj.ToString();2.Equals()判断两个对象是否相等。
bool isEqual obj1.Equals(obj2);3.GetHashCode()获取对象的哈希码。
int hashCode obj.GetHashCode();4.GetType()获取对象的类型。
Type type obj.GetType();5.MemberwiseClone()创建当前对象的浅表副本
object clone obj.MemberwiseClone();6.ReferenceEquals()判断两个对象的引用是否相等。
bool isSameReference object.ReferenceEquals(obj1, obj2);以下是一个示例代码演示了如何使用Object类的方法和属性
class MyClass
{//重写父类object的tostring()方法默认输出namespceclassnamepublic override string ToString(){return This is MyClass;}//重写父类equals方法默认和功能一样值类型比较值是否相等引用类型比较引用地址是否相同string 比较字符串内容是否相同。public override bool Equals(object obj){if (obj null || GetType() ! obj.GetType()){return false;}MyClass other (MyClass)obj;// 判断两个对象的特定属性是否相等return this.Property other.Property;}public override int GetHashCode(){return this.Property.GetHashCode();}public string Property { get; set; }
}class Program
{static void Main(string[] args){MyClass obj1 new MyClass { Property Value1 };MyClass obj2 new MyClass { Property Value2 };// 调用ToString()方法Console.WriteLine(obj1.ToString());// 调用Equals()方法bool isEqual obj1.Equals(obj2);Console.WriteLine(isEqual);// 调用GetHashCode()方法int hashCode obj1.GetHashCode();Console.WriteLine(hashCode);// 调用GetType()方法Type type obj1.GetType();Console.WriteLine(type.Name);// 调用MemberwiseClone()方法MyClass clone (MyClass)obj1.MemberwiseClone();Console.WriteLine(clone.Property);// 调用ReferenceEquals()方法bool isSameReference object.ReferenceEquals(obj1, obj2);Console.WriteLine(isSameReference);}
}
注意Object类中的Equals()方法判断两个对象是否相等默认使用的是引用相等比较。如果需要自定义相等性的判断逻辑可以在类中重写Equals()方法。同时还可以重写和!运算符来实现相等性比较