简体   繁体   中英

Pass Type as parameter and check

I want to build a method that accepts parameter as Type like

void M1(Type t)
{
  // check which type it is
}

and call it like

M1(typeof(int));

I have no idea how to check type in method body.

I have tried

if (t is double)

But it is giving warning

The given expression never provided type (double)

Please help me for checking the type of parameter.

If you want to check for an exact type, you can use:

if (t == typeof(double))

That's fine for double , given that it's a struct, so can't be inherited from.

If you want to perform a more is-like check - eg to check whether a type is compatible with System.IO.Stream - you can use Type.IsAssignableFrom :

if (typeof(Stream).IsAssignableFrom(t))

That will match if t is System.IO.MemoryStream , for example (or if it's System.IO.Stream itself).

I always find myself having to think slightly carefully to work out which way round the call goes, but the target of the call is usually a typeof expression.

You can try

  if(t == typeof(double))

or

 if (typeof(double).IsAssignableFrom(t))

or

 if(t == default(double).GetType())

or

 if(t.Name == "Double")

Personally i prefer the first option

Have a look at IsAssignableFrom , which determines whether an instance of a specified type can be assigned to the current type instance.

public void M<T>(T value) 
{
    if (typeof(T).IsAssignableFrom(typeof(double)))
        Console.Write("It's a double");  
}

It returns true if the given parameter:

  • represents the same type.

  • is derived either directly or indirectly from the current instance.

  • is a generic type parameter, and the current instance represents one of the constraints of the parameter.

  • represents a value type, and the current instance represents Nullable (Nullable(Of paramerter) in Visual Basic).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM