如何检查给定对象是否可为空,换句话说如何实现以下方法...
bool IsNullableValueType(object o)
{
...
}
Run Code Online (Sandbox Code Playgroud)
编辑:我正在寻找可以为空的值类型.我没有记住ref类型.
//Note: This is just a sample. The code has been simplified
//to fit in a post.
public class BoolContainer
{
bool? myBool = true;
}
var bc = new BoolContainer();
const BindingFlags bindingFlags = BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance
;
object obj;
object o = (object)bc;
foreach (var fieldInfo in o.GetType().GetFields(bindingFlags))
{
obj = (object)fieldInfo.GetValue(o);
}
Run Code Online (Sandbox Code Playgroud)
obj现在指的是type bool(System.Boolean)的对象,其值等于true.我真正想要的是一个类型的对象Nullable<bool>
所以现在作为一个解决方法我决定检查o是否可以为空并在obj周围创建一个可空的包装器.
我正在阅读Anders Hejlsberg等的第4版"C#编程语言"一书.
有几个定义有点扭曲:
未绑定的泛型类型:泛型类型声明本身表示未绑定的泛型类型...
构造类型:包含至少一个类型参数的类型称为构造类型.
open type:open类型是一种涉及类型参数的类型.
闭合类型:闭合类型是不是开放类型的类型.
unbound type:指非泛型类型或非绑定泛型类型.
bound类型:指非泛型类型或构造类型.[annotate] ERIC LIPPERT:是的,非泛型类型被认为是绑定和未绑定的.
问题1,是否低于我列出的正确值?
int //non-generic, closed, unbound & bound,
class A<T, U, V> //generic, open, unbound,
class A<int, U, V> //generic, open, bound, constructed
class A<int, int, V> //generic, open, bound, constructed
class A<int, int, int> //generic, closed, bound, constructed
Run Code Online (Sandbox Code Playgroud)
问题2,书中说"未绑定类型是指由类型声明声明的实体.未绑定泛型类型本身不是类型,它不能用作变量,参数或返回值的类型,或者一个基本类型.唯一可以引用未绑定泛型类型的构造是typeof表达式(第7.6.11节)." 很好,但下面是一个可以编译的小测试程序:
public class A<W, X> { }
// Q2.1: how come unbounded generic type A<W,X> can be used as a …Run Code Online (Sandbox Code Playgroud)