您的位置:首页 > 编程语言 > Java开发

Java5.0与C#2.0的区别之一:Struct类型

2006-12-10 22:22 381 查看
注意:以下如果没有具体说明版本号, Java一律表示Java5.0, C#一律表示C#2.0

在Java中没有Struct关键字, 但C#有. 在C#中, Struct与Class的区别有以下几点:
1. Struct是值类型(Value type),但Class是引用类型(reference type), structs在managed stack中被创建, classes在managed heap中被创建
2. Struct不支持继承,但Class支持,所以Struct的成员不能被protected修饰
3. 不能为Struct提供默认构造函数和析构函数
4. Struct的实例成员不能在声明的时候进行初始化
5. Struct可以实现接口, 也可以包含constructors, constants, fields, methods, properties, indexers, operators, events, 和nested types, 但要包含上述成员时, 建议优先考虑用Class

下面是一个Struct的Sample

using System;

using System.Collections.Generic;

using System.Text;
namespace ConsoleApp

{

public class StructTest

{

static void Main()

{

Book b1 = new Book(15.2, "Effective C#", "Bill");

Book b2 = new Book(18.5, "Effective Java", "Joshua");

if (b2 >= b1)

{

b1.log("b2 is greater than or equal to b1");

}

}

}
public struct Book:ICloneable

{

private double d_price;

private string s_title;

private string s_author;
//private string s_author="Jash"; //Error, Can't have instance field initializers in struct

public const string Type = "novel";
public Book(double _price,string _title,string _author)

{

d_price = _price;

s_title = _title;

s_author = _author;

log("In Constructor of struct Book");

}
internal void log(String msg)

{

Console.WriteLine(msg);

}
public String this[string field]

{

get

{

if (field.Equals("title")) return title;

else if (field.Equals("author")) return author;

else if (field.Equals("price")) return price.ToString();

else return null;

}

private set

{

if (field.Equals("title")) title = value;

else if (field.Equals("author")) author = value;

else if (field.Equals("price")) price = Double.Parse(value);

}
}
public double price

{

get

{

return d_price;

}

private set

{

d_price = value;

}

}
public string title

{

get

{

return s_title;

}

set

{

s_title = value;

}

}
public string author

{

get

{

return s_author;

}

set

{

s_author = value;

}

}
public object Clone()

{

return null;

}
//overload operator ">="

public static bool operator >= (Book src,Book target)

{

if (src.price >= target.price) return true;

else return false;

}
public static bool operator <= (Book src, Book target)

{

if (src.price <= target.price) return true;

else return false;

}
//nested reference type in enclosing struct

public class Nested

{

Nested() { }

}
//nested struct in enclosing struct

public struct NestedStruct

{

}

}

}

运行这个程序的结果如下:

In Constructor of struct Book

In Constructor of struct Book

b2 is greater than or equal to b1

price:18.5,title:Effective Java,author:Joshua

price:15.2,title:Effective C#,author:Bill
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: