在通用可空T上实施使用 [英] On Generic Nullable<T> implementation use
问题描述
我正在通过考试参考70-483:用C#编程"进行操作.由Wouter de Kort撰写的"Generic Nullable< T"示例是"Generic Nullable< T"示例.实施" (清单2-13).我对如何使用–使用–结构感到困惑.以下
是那个清单.任何点击-技巧-资源指示都将不胜感激.
struct Nullable< T>其中T:struct
{
私人布尔hasValue;
私有T值;
公共Nullable(T值)
{
this.hasValue = true;
this.value = value;
}
公共布尔HasValue {获取{return this.hasValue; }}
公共T值
{
get
{
如果(!this.HasValue)抛出新的ArgumentException();
返回this.value;
}
}
public T GetValueOrDefault()
{
返回this.value;
}
}
I am working through "Exam Ref 70-483: Programming in C#" by Wouter de Kort and in the generics section is an example "Generic Nullable<T> implementation" (Listing 2-13). I am confused as to how to consume – use – the struct. Below
is that listing. Any hits – tips – directions to resources, would be greatly appreciated.
struct Nullable<T> where T : struct
{
private bool hasValue;
private T value;
public Nullable(T value)
{
this.hasValue = true;
this.value = value;
}
public bool HasValue { get { return this.hasValue; } }
public T Value
{
get
{
if (!this.HasValue) throw new ArgumentException();
return this.value;
}
}
public T GetValueOrDefault()
{
return this.value;
}
}
谢谢,
山姆
推荐答案
Nullable< T>是系统类型.您不会在C#中直接使用它.相反,您只是使用T?其中T是任何值类型.这是Nullable T的别名.因此诠释?变为Nullable< int>和DateTime?变为Nullable< DateTime>.
Nullable<T> is a system type. You don't use it directly in C#. Instead you simply use T? where T is any value type. This is an alias for Nullable<T>. Hence int? becomes Nullable<int> and DateTime? becomes Nullable<DateTime>.
主要用法是从数据库中检索可为空的数据,但它也用于指示可选值.例如,您可能有一个存储在数据库中的Employee,而他们可能对主管有FK.但是,并不是每个员工都可以有一名主管. 因此,数据库将允许FK为空.如果您想映射到该表,则可以执行以下操作.
The primary usage is for retrieving nullable data from the database but it is also used to indicate optional values. As an example you might have an Employee stored in a database and they may have a FK to a supervisor. But not every employee may have a supervisor. So the database would allow a null for the FK. If you wanted to map to this table you'd do something like this.
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public int? SupervisorId { get; set; }
}
//Later when wanting to use the value
var employee = new Employee();
...
//Using Value will throw exception if HasValue is false
if (employee.Supervisor.Id.HasValue)
GetSupervisor(employee.SupervisorId.Value);
//Alternative approach
GetSupervisor(employee.SupervisorId.GetValueOrDefault());
另一个示例是可选参数,但我倾向于不同意这种方法.
Another example is for optional parameters but I tend to disagree with this approach.
void Foo ( string message, int? optionalValue = null )
{
if (optionalValue.HasValue)
//Use optional value
}
迈克尔·泰勒
http://www.michaeltaylorp3.net
Michael Taylor
http://www.michaeltaylorp3.net
这篇关于在通用可空T上实施使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!