The following program outputs "We have something else". How do I properly determine a DataType of the type being passed in?
void Main()
{
AFunction(typeof(string));
}
void AFunction<T>(T aType) {
if (aType.GetType() == typeof(string)) {
Console.WriteLine ("We have a string");
} else {
开发者_运维知识库 Console.WriteLine ("We have something else");
}
}
Use the is
keyword.
if(aType is string)
Console.WriteLine("We have a string");
else
Console.WriteLine("We have something else");
One thing to note when using this kind of logic is that is
will return true for super-types which could lead to unexpected behavior:
if(myObj is object)
Console.WriteLine("This will always print");
else if(myObj is int)
Console.WriteLine("This will never print");
if you're looking for type from a (small) finite list, you can use 'is'.
I think you don't need to use Generic Type in this circumstance.
You just send an Object Type to the AFunction and then use the is
keyword as follows:
void AFunction(Object aType)
{
if (aType is string) {
Console.WriteLine ("We have a string");
} else {
Console.WriteLine ("We have something else");
}
}
By the way, I think that the Generic Type is not for this kind of usage.
typeof(string)
returns a Type
.
So the compiler infers that you mean to call AFunction<Type>(typeof(string))
.
GetType
returns a Type
that represents the type Type
for an instance of Type
.
typeof(Type)
does not equal typeof(string)
, so the result is exactly as expected.
Did you mean
AFunction<string>("Hello World");
void AFunction<T>(T value)
{
if (value is string) ...
}
or
AFunction(typeof(string));
void AFunction(Type type)
{
if (type == typeof(string)) ...
}
or
AFunction<string>();
void AFunction<T>()
{
if (typeof(T) == typeof(string)) ...
}
?
Using your current calls you could make AFunction something like this:
void AFunction<T>(T aType)
{
if ((aType as Type).Name == "String")
{
Console.WriteLine("We have a string");
}
else
{
Console.WriteLine("We have something else");
}
}
精彩评论