简体   繁体   English

如何避免从值类型的输出参数到接口的装箱?

[英]How to avoid boxing from output parameter of value type to interface?

While developing I run into a question about boxing of the output parameter of value type when implementing an interface.在开发时,我遇到了一个关于在实现接口时对值类型的输出参数进行装箱的问题。 How could I avoid boxing inside F method of IProvider interface from S[X] struct instance to IS interface ?如何避免在 IProvider 接口的 F 方法中从 S[X] 结构实例到 IS 接口的装箱?

Any help would be greatly appreciated.任何帮助将不胜感激。

interface IProvider
{
    bool F(out IS value); 
}

class ConcreteProvider1 : IProvider
{
    public bool F(out IS value)
    {
        value = new S1(1); // boxing S1 to IS
        return true; // some logic here
    }
}

class ConcreteProvider2 : IProvider
{
    public bool F(out IS value)
    {
        value = new S2("text"); // boxing S2 to IS
        return true; // some logic here
    }
}

interface IS { }
readonly struct S1 : IS
{
    public int Value1 { get; }
    public S1(int value) => Value1 = value;
}

readonly struct S2 : IS
{
    public string Value2 { get; }
    public S2(string value) => Value2 = value;
}

class Program
{
    static void Main(string[] args)
    {
        var result = new IProvider[] { new ConcreteProvider1(), new ConcreteProvider2() }
                            .Any(p => p.F(out var value));
    }
}

Possibly I should use static method Try[X] with specific value type for the output parameter可能我应该对输出参数使用具有特定值类型的静态方法 Try[X]

readonly struct S2 : IS
{
    public string Value2 { get; }
    public S2(string value) => Value2 = value;

    public static bool TryParse(out S2 s2)
    {
        s2 = new S2("text");
        return true;
    }
}

and call static methods instead of using Linq并调用静态方法而不是使用 Linq

var result = S2.TryParse(out var s2) || S1.TryParse(out var s1);

PS All code in question and answer just sample to more simply describe the question PS所有有问题的代码和答案只是示例以更简单地描述问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM