简体   繁体   English

通过类型作为参数并检查

[英]Pass Type as parameter and check

I want to build a method that accepts parameter as Type like 我想建立一个将参数接受为Type的方法

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. 我不知道如何检查方法正文中的type

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. 鉴于double是结构体,因此对于double来说是很好的,因此不能继承。

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 : 如果您想执行更多类似检查(例如,检查类型是否与System.IO.Stream兼容),则可以使用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). 例如,如果tSystem.IO.MemoryStream (或者它是System.IO.Stream本身),则将匹配。

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. 我总是发现自己必须仔细思考,才能确定调用的方向,但是调用的目标通常typeof表达式。

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. 看一下IsAssignableFrom ,它确定是否可以将指定类型的实例分配给当前类型的实例。

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: 如果给定参数,则返回true:

  • 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). 表示值类型,而当前实例表示Nullable(在Visual Basic中为Nullable(Of paramerter))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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