我有我認爲必須是一個共同的問題。可以說我有一個典型的Person類,我有一個汽車類,它有一個類型的人的場/業主:C#設置屬性/字段值爲none
public class Car
{
Person owner;
}
但有時我想要的車有沒有所有者。處理這個問題的建議方法是什麼? (可編輯:澄清,我的意思是你不能使用Person?owner;)
我可以添加一個布爾字段/屬性:hasOwner,但這似乎相當冗長,所以我覺得像這樣的人創造類人型的靜態成員沒有的:
namespace ConsoleApplication2
{
public class Person
{
public static Person none;
public int age;
static Person()
{
none = new Person();
}
}
public class Car
{
public Person owner;
}
class Program
{
static void Main(string[] args)
{
Car dumped = new Car();
dumped.owner = Person.none;
Console.ReadLine();
}
}
}
這編譯和運行,雖然我還沒有在實際應用中使用它。後來我想我可以做一個通用類與沒有成員像這樣:
namespace ConsoleApplication2
{
public class NoneMember<T> where T : new()
{
public static T none;
static NoneMember()
{
none = new T();
}
}
public class Person: NoneMember<Person>
{
}
public class Car
{
public Person owner;
}
class Program
{
static void Main(string[] args)
{
Car dumped = new Car();
dumped.owner = Person.none;
if (dumped.owner == Person.none)
Console.Write("This car has no owner");
Console.ReadLine();
}
}
}
編譯並運行了,雖然會有一個問題,如果你想繼承表格的人類,與通用和非通用versons。更多有經驗的c#程序員的想法將不勝感激。
編輯:使用null來表示none的問題是您不能將null作爲方法/構造函數參數傳遞。 null表示沒有設置的值,與value不同的是none。
Edit2:我想我得到的異常時,我傳遞null參數。不知道發生了什麼事。我不知道現在是否可以重現錯誤。
爲什麼設置'Person'變量'null'不一個選項? – Oded
同意,可以請你解釋一句「空類型不起作用引用類型已經爲空。」 –
@正好。爲什麼重新發明輪子? –