C# 中的 typeof 保留字是否有 Ruby 等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2192335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:16:35  来源:igfitidea点击:

Is there a Ruby equivalent for the typeof reserved word in C#?

c#ruby

提问by Chris

I have a C# method that I need to call from a piece of Ruby that requires a System.Type argument. Is there a Ruby equivalent to typeof in C#? The call will look something like this in C# ...

我有一个 C# 方法,我需要从一块需要 System.Type 参数的 Ruby 中调用它。在 C# 中是否有与 typeof 等效的 Ruby?调用在 C# 中看起来像这样......

var CustomClasInstance = Container.GetInstance(typeof(ICustomClass))

var CustomClasInstance = Container.GetInstance(typeof(ICustomClass))

采纳答案by RyanWilcox

In addition to checking Object#class (the instance method class on the Object aka Base class), you could

除了检查 Object#class(Object aka Base 类上的实例方法类),您还可以

s.is_a? Thing

this will check to see if s has Thing anywhere in its ancestry.

这将检查 s 是否在其祖先的任何地方都有 Thing 。

回答by jsalonen

For a reference on how to identify variable types in Ruby, see http://www.techotopia.com/index.php/Understanding_Ruby_Variables#Identifying_a_Ruby_Variable_Type

有关如何在 Ruby 中识别变量类型的参考,请参阅 http://www.techotopia.com/index.php/Understanding_Ruby_Variables#Identifying_a_Ruby_Variable_Type

If you have variable named s, you can retrieve the type of it by invoking

如果您有变量 named s,则可以通过调用来检索它的类型

s.class
s.class

回答by dtb

ICustomClass.to_clr_type

回答by bta

Either Object.classor Object.typeshould do what you need.

要么Object.classObject.type应该做你需要的。

Also, the two methods Object.is_a?and Object.instance_of?can be used. However, they are not 100% identical. The statement obj.instance_of?(myClass)will return true only if object objwas created as an object of type myClass. Using obj.is_a?(myClass)will return true if the object objis of class myClass, is of a class that has inherited from myClass, or has the module myClassincluded in it.

此外,这两种方法Object.is_a?,并Object.instance_of?可以使用。但是,它们并非 100% 相同。obj.instance_of?(myClass)仅当 objectobj被创建为 type 的对象时,该语句才会返回 true myClassobj.is_a?(myClass)如果对象obj属于 class myClass,属于从 继承的类myClass,或者包含模块,则Using将返回 true myClass

For example:

例如:

x = 1
x.class                   => Fixnum
x.instance_of? Integer    => false
x.instance_of? Numeric    => false
x.instance_of? Fixnum     => true
x.is_a? Integer           => true
x.is_a? Numeric           => true
x.is_a? Fixnum            => true

Since your C# method requires a very specific data type, I would recommend using Object.instance_of?.

由于您的 C# 方法需要非常特定的数据类型,因此我建议使用Object.instance_of?.