简体   繁体   English

埃菲尔:有没有一种方法可以在没有任何附加实例的情况下测试类的给定泛型参数?

[英]Eiffel: Is there a way to test a given Generic parameter of a Class without any attached instance of it?

Is there a way to test a given Generic parameter of a Class without any attached instance of it? 有没有办法在没有任何附加实例的情况下测试类的给定泛型参数?

class BAG[G -> MOUSE]

feature -- 

    discriminate
        do
            if G.conforms_to (MAMMAL) then
                io.putstring ("you gave me a real animal")
            elseif G.conforms_to (COMPUTER_ACCESSORY) then
                io.putstring ("Seems you don't like animals such as computers")
            else
                io.pustring ("Still dont know what you are dealing with")
            end
        end

You've almost nailed it. 您几乎钉死了它。 The missing part is curly braces and parentheses: 缺少的部分是花括号和括号:

        if ({G}).conforms_to ({MAMMAL}) then
            io.put_string ("You gave me a real animal.")
        elseif ({G}).conforms_to ({COMPUTER_ACCESSORY}) then
            io.put_string ("Seems you don't like animals such as computers.")
        else
            io.put_string ("Still don't know what you are dealing with.")
        end

Explanation: 说明:

  1. {FOO} , where FOO is a type name, stands for a type object. {FOO} (其中FOO是类型名称)代表类型对象。 It works for any type, including formal generics, thus {G} and {MAMMAL} . 它适用于任何类型,包括形式泛型,例如{G}{MAMMAL}
  2. The syntax {FOO}.bar is reserved for non-object calls. 语法{FOO}.bar保留用于非对象调用。 But here we want an object call on the type object. 但是这里我们要对类型对象进行对象调用。 Therefore, {G} is enclosed in parentheses: ({G}).conforms_to (instead of {G}.conforms_to ). 因此, {G}括在括号中: ({G}).conforms_to {G}.conforms_to (而不是{G}.conforms_to )。

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

相关问题 给定一个字符串作为泛型类的类型名称,我如何在运行时创建实例。 如果不可能,还有其他方法吗? - Given a string as the type name of a generic class, how can I create the instance in runtime. If it is not possible, Is there another way? 埃菲尔铁塔(Eiffel):对形式通用参数的无效约束 - Eiffel: Invalid constraint for formal generic paramete 通过类参数检查的泛型类型参数可以被黑,还有更好的方法吗? - Generic Type Argument checked by Class Parameter can be hacked, any better ways? 通过比较实例属性类型和泛型参数来约束泛型函数 - Constraint generic function by comparing instance property type with generic parameter 没有类定义的泛型方法 - Generic method without class definition Haskell中自定义类型类的通用实例? - Generic instance of custom type class in Haskell? 如何通过泛型传递参数:类 <Clazz<G> &gt; - How to pass parameter with generic: Class<Clazz<G>> 通用子类和类型推断-这是唯一的方法吗? - Generic child class and type inference - is this the only way? 有没有办法实现通用 class 以显示 object 字段? - Is there a way to implement a generic class for displaying an object fields? Factory方法,用于实例化泛型类中使用的对象的实例 - Factory method to instantiate instance of objects used in a generic class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM