我有我认为必须是一个共同的问题。可以说我有一个典型的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
同意,可以请你解释一句“空类型不起作用引用类型已经为空。” –
@正好。为什么重新发明轮子? –