.NET 4.0和C#4.0中的事件和委托违规 [英] Event and delegate contravariance in .NET 4.0 and C# 4.0

查看:164
本文介绍了.NET 4.0和C#4.0中的事件和委托违规的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调查这个问题时,我很好奇C#4.0中的新协方差/逆向特征如何影响它。 p>

在Beta 1中,C#似乎不同意CLR。回到C#3.0,如果你有:

  public event EventHandler< ClickEventArgs>点击; 

...然后你还有其他地方:

  button.Click + = new EventHandler< EventArgs>(button_Click); 

...编译器会barf,因为它们是不兼容的委托类型。但是在C#4.0中,它编译得很好,因为在CLR 4.0中,类型参数现在在中被标记为,所以它是相反的,因此编译器假定多播委托 + = 将工作。



这是我的测试:

  public class ClickEventArgs:EventArgs {} 

public class Button
{
public event EventHandler< ClickEventArgs>点击;

public void MouseDown()
{
Click(this,new ClickEventArgs());
}
}

class程序
{
static void Main(string [] args)
{
按钮按钮=新的Button();

button.Click + = new EventHandler< ClickEventArgs>(button_Click);
button.Click + = new EventHandler< EventArgs>(button_Click);

button.MouseDown();
}

static void button_Click(object s,EventArgs e)
{
Console.WriteLine(Button was click);
}
}

但是尽管它编译,但它不起作用运行时( ArgumentException :代理必须是相同的类型)。



只要添加任何一个两个代表类型。但是,当添加第二个组播时,两个不同类型的组合会导致异常。



我猜这是beta 1中的CLR中的一个错误(编译器的



发布候选人的更新:



上述代码不再编译。必须在 EventHandler< TEventArgs> 委托类型中的 TEventArgs 的相反性已经回滚了,所以现在代理具有与.NET 3.5相同的定义。



也就是说,我看过的测试版必须有:



public delegate void EventHandler< in TEventArgs>(object sender,TEventArgs e);

  

现在回到:

  public delegate void EventHandler< TEventArgs>(object sender,TEventArgs e); 

但是 Action< T> 委托参数 T 仍然是逆向的:

  public delegate void Action< in T> (T obj); 

同样的, Func< T> T 是协变的。



这个妥协有很大的意义,只要我们假设主使用多播代理是在事件的上下文中。我个人发现,除了作为事件,我从不使用多播委托。



所以我猜C#编码标准现在可以采用一个新规则:不要组播多播代理通过协方差/逆向相关的多个委托类型。如果你不知道这是什么意思,只要避免使用 Action 来保护事件的安全。



当然,这个结论对于这个从...的原始问题 ...

解决方案

非常有趣。您不需要使用事件来看到这种情况,确实我觉得使用简单的代理更简单。



考虑 Func< string> Func< object> 。在C#4.0中,您可以将 Func< string> 隐式转换为 Func< object> ,因为您始终可以使用字符串引用为对象引用。但是,当您尝试组合它们时,出现问题。这是一个简短但完整的程序,以两种不同的方式显示问题:

  using System; 

class程序
{
static void Main(string [] args)
{
Func< string> stringFactory =()=> 你好;
Func< object> objectFactory =()=> new object();

Func< object> multi1 = stringFactory;
multi1 + = objectFactory;

Func< object> multi2 = objectFactory;
multi2 + = stringFactory;
}
}

这个编译很好,但是两个组合调用(被+ =语法糖隐藏)抛出异常。 (注释第一个看到第二个。)



这绝对是一个问题,虽然我不知道解决方案应该是什么。执行时可能代理代码需要根据所涉及的代理类型确定最合适的使用类型。这有点讨厌有一个通用的 Delegate.Combine 调用是相当不错的,但是您无法真正以有意义的方式表达相关类型。



值得注意的一点是协同转换是一个参考转换 - 在上面, multi1 stringFactory 指的是同一个对象:它不是与写作相同

  Func<对象> multi1 = new Func< object>(stringFactory); 

(此时,以下行将无异常执行。)在执行时,BCL真的要处理一个 Func< string> 和一个 Func< object> 它没有其他信息可以继续。



这是讨厌的,我认真希望它以某种方式得到修复。我会告诉Mads和Eric这个问题,所以我们可以得到更多的知情评论。


While investigating this question I got curious about how the new covariance/contravariance features in C# 4.0 will affect it.

In Beta 1, C# seems to disagree with the CLR. Back in C# 3.0, if you had:

public event EventHandler<ClickEventArgs> Click;

... and then elsewhere you had:

button.Click += new EventHandler<EventArgs>(button_Click);

... the compiler would barf because they're incompatible delegate types. But in C# 4.0, it compiles fine, because in CLR 4.0 the type parameter is now marked as in, so it is contravariant, and so the compiler assumes the multicast delegate += will work.

Here's my test:

public class ClickEventArgs : EventArgs { }

public class Button
{
    public event EventHandler<ClickEventArgs> Click;

    public void MouseDown()
    {
        Click(this, new ClickEventArgs());
    }
}

class Program
{    
    static void Main(string[] args)
    {
        Button button = new Button();

        button.Click += new EventHandler<ClickEventArgs>(button_Click);
        button.Click += new EventHandler<EventArgs>(button_Click);

        button.MouseDown();
    }

    static void button_Click(object s, EventArgs e)
    {
        Console.WriteLine("Button was clicked");
    }
}

But although it compiles, it doesn't work at runtime (ArgumentException: Delegates must be of the same type).

It's okay if you only add either one of the two delegate types. But the combination of two different types in a multicast causes the exception when the second one is added.

I guess this is a bug in the CLR in beta 1 (the compiler's behaviour looks hopefully right).

Update for Release Candidate:

The above code no longer compiles. It must be that the contravariance of TEventArgs in the EventHandler<TEventArgs> delegate type has been rolled back, so now that delegate has the same definition as in .NET 3.5.

That is, the beta I looked at must have had:

public delegate void EventHandler<in TEventArgs>(object sender, TEventArgs e);

Now it's back to:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

But the Action<T> delegate parameter T is still contravariant:

public delegate void Action<in T>(T obj);

The same goes for Func<T>'s T being covariant.

This compromise makes a lot of sense, as long as we assume that the primary use of multicast delegates is in the context of events. I've personally found that I never use multicast delegates except as events.

So I guess C# coding standards can now adopt a new rule: don't form multicast delegates from multiple delegate types related through covariance/contravariance. And if you don't know what that means, just avoid using Action for events to be on the safe side.

Of course, that conclusion has implications for the original question that this one grew from...

解决方案

Very interesting. You don't need to use events to see this happening, and indeed I find it simpler to use simple delegates.

Consider Func<string> and Func<object>. In C# 4.0 you can implicitly convert a Func<string> to Func<object> because you can always use a string reference as an object reference. However, things go wrong when you try to combine them. Here's a short but complete program demonstrating the problem in two different ways:

using System;

class Program
{    
    static void Main(string[] args)
    {
        Func<string> stringFactory = () => "hello";
        Func<object> objectFactory = () => new object();

        Func<object> multi1 = stringFactory;
        multi1 += objectFactory;

        Func<object> multi2 = objectFactory;
        multi2 += stringFactory;
    }    
}

This compiles fine, but both of the Combine calls (hidden by the += syntactic sugar) throw exceptions. (Comment out the first one to see the second one.)

This is definitely a problem, although I'm not exactly sure what the solution should be. It's possible that at execution time the delegate code will need to work out the most appropriate type to use based on the delegate types involved. That's a bit nasty. It would be quite nice to have a generic Delegate.Combine call, but you couldn't really express the relevant types in a meaningful way.

One thing that's worth noting is that the covariant conversion is a reference conversion - in the above, multi1 and stringFactory refer to the same object: it's not the same as writing

Func<object> multi1 = new Func<object>(stringFactory);

(At that point, the following line will execute with no exception.) At execution time, the BCL really does have to deal with a Func<string> and a Func<object> being combined; it has no other information to go on.

It's nasty, and I seriously hope it gets fixed in some way. I'll alert Mads and Eric to this question so we can get some more informed commentary.

这篇关于.NET 4.0和C#4.0中的事件和委托违规的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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