开发者

Using anonymous generic types with multiple generics

开发者 https://www.devze.com 2023-01-05 02:31 出处:网络
After reviewing this blog by Kirill Osenkov (How to create a generic List of anonymous types?) I am trying to do something a little more advanced and having issues.

After reviewing this blog by Kirill Osenkov (How to create a generic List of anonymous types?) I am trying to do something a little more advanced and having issues.

The following code compiles:

    var anon = new { One = "1", Two = "2" };
    var result = DoSomething(anon);

    public static T DoSomething<T&g开发者_如何学Pythont;(T value)
    {
        return value;
    }

But if I try to add an additonal generic type, I cannot get it to build:

    var anon = new { One = "1", Two = "2" };
    var result = DoSomethingElse<int>(anon);

    public static T2 DoSomethingElse<T, T2>(T value)
        where T2 : new()
    {
        return new T2();
    }

Since I have no way of specifiying that T is typeof(anon), I can't seem to get it to infer this when given a type for T2. Is this possible?


No. This type of feature is not supported by the C# compiler. You must either manually specify all generic parameters or none and rely on type inference.

The closest you'll get is the following

var anon = new { One = "1", Two = "2" };
var result = DoSomethingElse(anon,42);

public static T2 DoSomethingElse<T, T2>(T value, T2 otherValue)
    where T2 : new()
{
    return new T2();
}


Not really a satisfying answer, but you could do the following, if you can tolerate writing a different version of DoSomethingWithT2 for each type T2:

var anon = new { One = "1", Two = "2" };
var result = DoSomethingWithInt(anon);

public static int DoSomethingWithInt<T>(T value)
{
    return DoSomethingElse<T, int>(value);
}

public static T2 DoSomethingElse<T, T2>(T value) where T2 : new()
{
    return new T2();
}

The correct-est answer is just to stop using an anonymous type here and use a tuple or define your own type. Sorry.

0

精彩评论

暂无评论...
验证码 换一张
取 消