how to decide a nullable value type
void Main()
{
test((int?)null);
test((bool?)null);
test((DateTime?)null);
}
void test(object p)
{开发者_JAVA技巧
//**How to get the type of parameter p**
}
Maybe this can help :
void Main()
{
test<int>(null);
test<bool>(null);
test<DateTime>(null);
}
void test<T>(Nullable<T> p)
where T : struct, new()
{
var typeOfT = typeof(T);
}
You cannot get the type because you didn't pass any value. There is no difference between the three invocations.
Casting a null
value is only useful to make the compiler pick a specific overload of a function. Since you don't have an overloaded function here, the same function is called in all three cases. Without actually passing in a value, all your function will see is a null
value, it cannot determine the type the caller cast that null
value to.
Every object in .NET has a GetType()
method:
var type = p.GetType();
However, if you are trying to figure out the type of a parameter in this way, it is usually a sign that you're doing something wrong. You may want to look into overloaded methods or generics instead.
Edit
As an astute commenter pointed out, null
has no type associated with it. For example:
((int?)null) is int?
The above expression will yield false
. However, using generics, you can figure out what type the compiler expected the object to have:
void Test<T>(T p)
{
Type type = typeof(T);
...
}
Again, I maintain that this sort of strategy is generally avoidable, and if you can explain why you need it, we can probably help you more.
Do you mean the class name? That would get it:
if(p != null)
{
p.GetType().FullName.ToString();
}
Or only the type:
p.GetType();
Like this
If p IsNot nothing then
GetType(p).GetGenericArguments()(0)
End If
(I assumed you were looking for the generic type, as getting the type of the object itself is quite simple)
In addition to GetType, you can use the is keyword like so:
void test(object p) {
if (p is int?) {
// p is an int?
int? i = p as int?;
}
else if (p is bool?) {
// p is an bool?
bool? b = p as bool?;
}
}
If p is null, then it could be int?
or bool?
, or any object
or Nullable
type.
One optimization is to use as keyword directly, like so:
void test(object p) {
if (p == null)
return; // Could be anything
int? i = p as int?;
if (i != null) {
// p is an int?
return;
}
bool? b = p as bool?;
if (b != null) {
// p is an bool?
return;
}
}
精彩评论