相关疑难解决方法(0)

为什么在值类型上调用显式接口实现会导致它被装箱?

我的问题与此问题有些相关:泛型约束如何阻止使用隐式实现的接口对值类型进行装箱?,但不同,因为它不需要约束来执行此操作,因为它根本不是通用的.

我有代码

interface I { void F(); }
struct C : I { void I.F() {} }
static class P {
    static void Main()
    {    
        C x;
        ((I)x).F();
    }
}
Run Code Online (Sandbox Code Playgroud)

主要方法编译如下:

IL_0000:  ldloc.0
IL_0001:  box        C
IL_0006:  callvirt   instance void I::F()
IL_000b:  ret
Run Code Online (Sandbox Code Playgroud)

为什么不编译到这个?

IL_0000:  ldloca.s   V_0
IL_0002:  call       instance void C::I.F()
IL_0007:  ret
Run Code Online (Sandbox Code Playgroud)

我明白为什么你需要一个方法表来进行虚拟调用,但在这种情况下你不需要进行虚拟调用.如果接口正常实现,则不进行虚拟呼叫.

还相关:为什么显式接口实现是私有的? - 关于这个问题的现有答案没有充分解释为什么这些方法在元数据中被标记为私有(而不是仅仅具有不可用的名称).但即使这样也没有完全解释为什么它是盒装的,因为从C里面调用时它仍然是盒子.

.net c# boxing interface explicit-interface

15
推荐指数
1
解决办法
1232
查看次数

明确实现的接口和泛型约束

interface IBar { void Hidden(); }

class Foo : IBar { public void Visible() { /*...*/ } void IBar.Hidden() { /*...*/ } }

class Program
{
    static T CallHidden1<T>(T foo) where T : Foo
    {
        foo.Visible();
        ((IBar)foo).Hidden();   //Cast required

        return foo;
    }

    static T CallHidden2<T>(T foo) where T : Foo, IBar
    {
        foo.Visible();
        foo.Hidden();   //OK

        return foo;
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有任何区别(CallHidden1与CallHidden2)是实际编译的代码?T:Foo和T:Foo,IBar(如果Foo实现IBar)在访问显式实现的接口成员时是否存在其他差异?

c# generics explicit-interface

7
推荐指数
2
解决办法
803
查看次数

IDictionary和IReadOnlyDictionary的扩展方法

我的问题类似于前一个问题,但这个问题的答案不适用于此问题.

好吧,我想为两者IDictionary和IReadOnlyDictionary接口编写扩展方法:

public static TValue? GetNullable<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
    where TValue : struct
{
    return dictionary.ContainsKey(key)
        ? (TValue?)dictionary[key]
        : null;
}

public static TValue? GetNullable<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
    where TValue : struct
{
    return dictionary.ContainsKey(key)
        ? (TValue?)dictionary[key]
        : null;
}
Run Code Online (Sandbox Code Playgroud)

但是当我将它用于实现两个接口的类(例如Dictionary<Tkey, TValue>)时,我得到了"模糊的调用".我不想打字var value = myDic.GetNullable<IReadOnlyDictionary<MyKeyType, MyValueType>>(key),我希望它只是var value = myDic.GetNullable(key).

这可能吗?

c# idictionary

7
推荐指数
2
解决办法
2204
查看次数