Csharp/C#教程:用C ++编写事件并用C#处理它们分享


用C ++编写事件并用C#处理它们

我有一台带有一些数字I / O引脚的工业计算机。 制造商提供了一些C ++库和示例来处理引脚状态更改。

我需要将这些事件集成到C#应用程序中。 AFAIK执行此操作的最简单方法是:

  1. 为从DIO引脚发出中断时触发事件的制造商库创建托管C ++ / CLI包装器。
  2. 引用包装并处理C#部分中的事件,因为它们是正常的C#事件。

我试图用一些没有运气的模拟对象来完成这项工作。 从文档中,函数EventHandler应该完成我案例中的大部分“脏工作”。 以下有关旧线程和MSDN文档中的EventHandler示例的信息,我最终得到了以下测试代码:

C ++ / CLI

using namespace System; public ref class ThresholdReachedEventArgs : public EventArgs { public: property int Threshold; property DateTime TimeReached; }; public ref class CppCounter { private: int threshold; int total; public: CppCounter() {}; CppCounter(int passedThreshold) { threshold = passedThreshold; } void Add(int x) { total += x; if (total >= threshold) { ThresholdReachedEventArgs^ args = gcnew ThresholdReachedEventArgs(); args->Threshold = threshold; args->TimeReached = DateTime::Now; OnThresholdReached(args); } } event EventHandler^ ThresholdReached; protected: virtual void OnThresholdReached(ThresholdReachedEventArgs^ e) { ThresholdReached(this, e); } }; public ref class SampleHandler { public: static void c_ThresholdReached(Object^ sender, ThresholdReachedEventArgs^ e) { Console::WriteLine("The threshold of {0} was reached at {1}.", e->Threshold, e->TimeReached); Environment::Exit(0); } }; void main() { return; CppCounter^ c = gcnew CppCounter(20); c->ThresholdReached += gcnew EventHandler(SampleHandler::c_ThresholdReached); Console::WriteLine("press 'a' key to increase total"); while (Console::ReadKey(true).KeyChar == 'a') { Console::WriteLine("adding one"); c->Add(1); } } 

C#

 using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { CppCounter cc = new CppCounter(5); //cc.ThresholdReached += cs_ThresholdReached; //= threshold) { ThresholdReachedEventArgs args = new ThresholdReachedEventArgs(); args.Threshold = threshold; args.TimeReached = DateTime.Now; OnThresholdReached(args); } } protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) { EventHandler handler = ThresholdReached; if (handler != null) { handler(this, e); } } public event EventHandler ThresholdReached; } public class ThresholdReachedEventArgs : EventArgs { public int Threshold { get; set; } public DateTime TimeReached { get; set; } } } 

我究竟做错了什么? 这是我缺少的东西吗?

  public class ThresholdReachedEventArgs : EventArgs 

代码是正确的,除了这个小故障。 您不小心在C#代码中重新声明了此类。 现在有两个 ,一个来自您的C ++ / CLI项目,另一个来自您的C#项目。 这是一个问题,.NET中的类型标识不仅仅由命名空间名称和类名决定,它还包括它来自的程序集。

所以这些是两种不同的类型,编译器试图告诉你它的C#版本不正确。 它们具有相同的名称并不能完全帮助您解码错误消息:)

很容易修复,只需从C#代码中删除类声明。 现在编译器将使用它的C ++ / CLI版本。

上述就是C#学习教程:用C ++编写事件并用C#处理它们分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/955268.html

(0)
上一篇 2021年11月21日
下一篇 2021年11月21日

精彩推荐