خرید بک لینک

I have the following union (C# 15+):

public union ValueSource(int, Func<int>);

As per the docs:

An implicit union conversion exists from each case type to the union type

So I expect both of the following to work:

ValueSource src1 = 42;
ValueSource src2 = () => 42;

However, the assignment to src2 fails with:

CS1660: Caot convert lambda expression to type 'ValueSource' because it is not a delegate type

Moreover, if I have this static method:

public class IntSource
{
    public static int Get() => 42;
}

The following assignment also fails:

ValueSource src3 = IntSource.Get;

with:

CS0428: Caot convert method group 'Get' to non-delegate type 'ValueSource'. Did you intend to invoke the method?

Why can I not do this when the very purpose of union types, by definition, is to allow each case type to be assignable to it? The docs also say:

Union conversions work by calling the corresponding generated constructor.

Which means the assignments are implicitly lowered to the union's generated struct constructor. So ValueSource src1 = 42 is actually ValueSource src1 = new ValueSource(42).

And the following works too:

ValueSource src4 = new(() => 10);

ValueSource src5 = new(IntSource.Get);

A messy explicit cast also works:

ValueSource src6 = (Func<int>) (() => 10);

What's stopping the compiler from allowing the assignments to src2 and src3?

برچسب: نویسنده: استخدام کار تاريخ: شنبه 30 آبان 1405 ساعت: 17:40

صفحه بندی