Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否有方法将参数传递给Is运算符?_C#_Generics - Fatal编程技术网

C# 是否有方法将参数传递给Is运算符?

C# 是否有方法将参数传递给Is运算符?,c#,generics,C#,Generics,我正在尝试找到以下选项的替代方案,以便利用is运算符 public bool IsOfType(Type type) { return this._item.GetType() == type; } 类似于以下内容的内容,不编译 public bool IsOfType(Type type) { return this._item is type; } 我想你在寻找: 或者,如果您可以将该方法设置为泛型,则更简单,因为您可以将is与类型参数一起使用: public bool

我正在尝试找到以下选项的替代方案,以便利用
is
运算符

public bool IsOfType(Type type)
{
    return this._item.GetType() == type;
}
类似于以下内容的内容,不编译

public bool IsOfType(Type type)
{
    return this._item is type;
}

我想你在寻找:

或者,如果您可以将该方法设置为泛型,则更简单,因为您可以将
is
与类型参数一起使用:

public bool IsOfType<T>()
{
    return _item is T;
}

根据上下文,您可以执行多项操作:

  • 如果只有两个类型实例,请使用
    Type.IsAssignableFrom(Type)
  • 如果您有权访问要比较的实例,请使用
    Type.IsInstanceOf(对象实例)
  • 使用泛型,如:

    public bool IsOfType()
    {
    返回此项。\u项为T;
    }
    

即将发布泛型替代品。。。为什么我必须看到更新的答案?:)我一直不喜欢InstanceOf syntax,为了避免它,把它作为
object
上的扩展方法几乎是值得的。@demoncodemonkey:是的,我知道你的意思。显然,语法本身在.NET1.0中是无法改进的,但我想知道是否有更好的名称可用…名称令人困惑。此外,这个答案有一个拼写错误,省略了
IsInstanceOf
的前两个字母。而且,对我来说,
这个名字是可识别的。我总是要三思而后行才能确定我们的答案是:它是
t.IsAssignableFrom(s)
s.IsAssignableFrom(t)
我需要。@Jeppe:x.IsAssignableFrom(y)我经常使用的一个技巧是,你可以在你的头脑中执行一个重写:x=(x)y;然后再解释一下这是否合适。我想这就是他们选择这个名字的原因。因此,y.IsInstanceOfType(x)x.IsAssignableFrom(y)。我忘记了Type.IsInstanceOf。啊!将用一个完整的例子编辑我的答案…它实际上被称为
IsInstanceOfType
,而不仅仅是
IsInstanceOf
public bool IsOfType<T>()
{
    return _item is T;
}
public bool IsOfType(Type type)
{
    return type.InstanceOf(_item);
}
public bool IsOfType<T>()
{
    return this._item is T;
}