• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

UndocumentedKeywordsinC#

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

研究Int32&的时候,无意中发现C#里面还有4个Undocument Keyword, 分别是__makeref, __reftype, __refvalue 以及__arglist。 其中前三个keyword可以这样用:

        int i = 1;
        
        TypedReference tr 
= __makeref(i);
        Type t 
= __reftype(tr); //t = System.Int32
        
        
int i1 = __refvalue(tr, int); //i1 = 1
        int i2 = (int)TypedReference.ToObject(tr); //i2 = 1
        
        i
++//i = 2
        
        
int i3 = __refvalue(tr, int); //i3 = 2

(关于TypedReference类型MSDN是这样描述的:Describes objects that contain both a managed pointer to a location and a runtime representation of the type that may be stored at that location. 同时TypedReference有[CLSCompliant(false)]标记)

于是我们可以用下面这种方法来模拟ByRef的参数

public class MyClass
}

比较不爽的就是我们必须在Foo方法体中判断TypedReference包含的类型。

注意如果把Foo写成public static void Foo(ref TypedReference tr),编译器会抱怨说:Method or delegate parameter cannot be of type 'ref System.TypedReference'。

至于__arglist则可以模拟params关键字,抄个例子:

public void Function(__arglist) 
}

调用它:Function(__arglist(2,3,4));  输出2,3,4

后注:这4个keyword毕竟是undocument的,微软也没有提供任何支持,所以不排除以后被delete掉。Mono下面的编译器似乎也不支持,不过我在vs2005 beta里面试验还是有效的。

 Updated: Flier Lu在他的blog对__arglist的使用作了更深入的探讨,推荐阅读。 :)


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中StreamReader读取中文时出现乱码问题总结发布时间:2022-07-10
下一篇:
C#文件比较差异发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap