如何正确访问 c++/CLI initonly TimeSpan 字段? [英] How to properly access c++/CLI initonly TimeSpan field?

查看:25
本文介绍了如何正确访问 c++/CLI initonly TimeSpan 字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码编译时出现警告和智能感知错误:

The following code compiles with warning and intellisense error:

ref class Test {
    initonly static TimeSpan Delay = TimeSpan(1,1,1); 

    Test() {
        long long ticks = Delay.Ticks; // << problem
    }
};

问题是:

  • 警告 C4395:'System::TimeSpan::Ticks::get':成员函数将在 initonly 数据成员 'Test::Delay' 的副本上调用
  • IntelliSense:不允许使用 initonly 字段的地址

如何正确访问 Ticks?

How to access Ticks properly?

推荐答案

嗯,这是非常重要的失败鲸鱼.警告是准确的,编译器对 TimeSpan::Tick 属性获取器的了解不够.它不能确保 getter 不会做任何可能改变结构值的事情,从而使 initonly 合同无效.它通过制作结构的副本来解决它并警告它,因为这可能是一个性能问题.这有点笨手笨脚,其他托管编译器制作副本而没有对此进行任何说明.我只是在它前面插入一个 #pragma warning(disable:4395) 以便抑制警告.

Well, that's pretty major fail-whale. The warning is accurate, the compiler doesn't know enough about the TimeSpan::Tick property getter. It cannot ensure that the getter doesn't do anything that might alter the value of the struct and thereby invalidates the initonly contract. It solves it by making a copy of the struct and warns about it since this is a possible perf issue. That's a bit heavy-handed, other managed compilers make the copy without saying anything about it. I'd just plunk a #pragma warning(disable:4395) ahead of it so the warning is suppressed.

IntelliSense 错误仅在我在 VS2012 中尝试时出现.那是一个错误.您可以在 connect.microsoft.com 上报告.

The IntelliSense error only appears when I try this in VS2012. That's a bug. You can report it at connect.microsoft.com.

考虑到痛苦和这似乎是一个私人班级成员,我只是放弃initonly 以取得成功.如果这是不可取的,那么您可以用属性包装该字段,有意创建副本,从而摆脱这两个问题,如下所示:

Given the misery and that this appears to be a private class member, I'd just drop initonly to get ahead. If that's not desirable then you can wrap the field with a property, intentionally creating the copy, and thus get rid of both problems, like this:

ref class Test {
    initonly static TimeSpan _delay = TimeSpan(1,1,1); 
    static property TimeSpan Delay { 
        TimeSpan get() { return _delay; }
    }

    Test() {
        long long ticks = Delay.Ticks;
    }
};

抖动优化器会摆脱它,所以不用担心开销.

The jitter optimizer will get rid of it so don't worry about overhead.

这篇关于如何正确访问 c++/CLI initonly TimeSpan 字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆