繁体   English   中英

指定类型的通用方法/类自定义实现

[英]Generic method/class custom implementation for specified type

有什么办法可以使此代码编译或其他替代方法。 此实现仅是示例。

namespace ConsoleApp3
{
    using System;

    public static class Temp<T>
        where T : struct
    {
        public static T DoSomething()
            => throw new NotImplementedException(); // common implementation

        public static int DoSomething()
            => 10; // custom implementation for specified type
    }
}

从阅读注释开始-如果意图是覆盖方法,则方法不能是静态的。 “常见”实现抛出NotImplementedException的示例代码表明,您不希望有一个基本实现,而只是被覆盖的实现。 在这种情况下,您可以这样做:

public abstract class Temp<T>
    where T : struct
{
    public abstract T GetDefault();
}

因为它是abstract您无法创建它的实例。 您必须创建继承的类。

public class IntTemp : Temp<int>
{
    public override int GetDefault()
    {
        // whatever your implmementation is
    }
}

我找到2个替代方法。

|               Method |     Mean |    Error |   StdDev | Allocated |
|--------------------- |---------:|---------:|---------:|----------:|
|     Benchmark_Single | 306.8 ns | 2.867 ns | 2.682 ns |       0 B |
| Benchmark_Reflection | 581.8 ns | 3.062 ns | 2.864 ns |       0 B |

--

namespace ConsoleApp3
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    public static class TempSingle<T>
        where T : struct
    {
        public static T DoCustom()
        {
            if (typeof(T) == typeof(int))
            {
                return (T)((object)int.MinValue);
            }
            else if (typeof(T) == typeof(ushort))
            {
                return (T)((object)ushort.MinValue);
            }

            return default;
        }
    }

    public static class TempReflection<T>
        where T : struct
    {
        public readonly static Func<T> Factory = GetFactory();

        private static int GetDefaultInt32()
        {
            return int.MinValue;
        }

        private static ushort GetDefaultUInt16()
        {
            return ushort.MinValue;
        }

        private static Func<T> GetFactory()
        {
            Type type = typeof(T);

            MethodInfo method = typeof(TempReflection<T>)
                .GetMethod($"GetDefault{type.Name}", BindingFlags.Static | BindingFlags.NonPublic);

            return Expression
                .Lambda<Func<T>>(Expression.Call(method))
                .Compile();
        }

        public static T DoCustom()
        {
            return default;
        }
    }
}

暂无
暂无

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

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