在运行时对 'object' 包含的基础类型使用扩展方法

Using Extension Methods on Underlying Type Contained by an 'object' at Runtime

我问了 question recently on the same project I'm working on,但这是一个关于扩展方法和对象类型的特定问题。

以下代码无效:

object ProcessField(byte [] buff, int position, Dictionary<int, Type> fields)
{
    int field = buff[position];
    position++;

    // Create an instance of the specified type.
    object value = Activator.CreateInstance(fields[field]);
    // Call an extension method for the specified type.
    value.DoSomething();

    return value;
}

public static void DoSomething(this Int32 value)
{
    // Do Something
}

public static void DoSomething(this Int16 value)
{
    // Do something...
}

编译器报错:

'object' does not contain a definition for 'DoSomething' and the best extension method overload 'DoSomething()' has some invalid arguments in blah blah...

似乎扩展方法未在运行时绑定,即使基础类型是 System.Int32 或 System.Int16(在运行时验证)。

有什么方法可以使这项工作(使用扩展方法)?它只是代码语义,还是在 'object' 上不在设计时转换它就不可能?

这...呃...真的很糟糕,但您可以使用 dynamic 实现您想要的效果。但是不要这样做。真的很糟糕。

object ProcessField(byte [] buff, int position, Dictionary<int, Type> fields)
{
    int field = buff[position];
    position++;  // this line really does absolutely nothing

    // dynamic is magic!
    dynamic value = Activator.CreateInstance(fields[field]);

    DoSomething(value);

    return value;
}