条件类型别名

本文关键字:别名 类型 条件 | 更新日期: 2023-09-27 18:22:20

我希望能够向用户提供一个选择-是使用16位索引(在OpenGL中)还是32位索引。在C++中,我可能只会为int或short创建一个别名,但在C#中我似乎没有这个选项。基本上,我的目标可以在下面的课程中总结:

using System;
namespace Something
{
    public class Conditional
    {
        public Conditional(Boolean is16Bit)
        {
            if (is16Bit)
            {
                SOMETYPE is Int16
            }
            else
            {
                SOMETYPE is Int32
            }
        }
        private List<SOMETYPE> _something;
    }
}

别名(如果可以的话)会更好——我只是不想强迫任何使用这段代码的人编写#define语句,这可能吗?

感谢

条件类型别名

似乎可以使用一个泛型:

namespace Something
{
    public class Conditional<T>
    {
        private List<T> _something = new List<T>();
        private Conditional()
        {
            // prevents instantiation except through Create method
        }
        public Conditional<T> Create()
        {
            // here check if T is int or short
            // if it's not, then throw an exception
            return new Conditional<T>();
        }
    }
}

创建一个:

if (is16Bit)
    return Conditional<short>.Create();
else
    return Conditional<int>.Create();

您可以使用一个接口和一个工厂,比如:

public interface IConditional
{
    void AddIndex(int i);
}
private class Conditional16 : IConditional
{
    List<Int16> _list = new List<Int16>();
    public void AddIndex(int i)
    {
        _list.Add((short)i);
    }
}
private class Conditional32 : IConditional
{
    List<Int32> _list = new List<Int32>();
    public void AddIndex(int i)
    {
        _list.Add(i);
    }
}
public static class ConditionalFactory
{
    public static IConditional Create(bool is16Bit)
    {
        if (is16Bit)
        {
            return new Conditional16();
        }
        else
        {
            return new Conditional32();
        }
    }
}

您的代码(及其调用方)可以对IConditional执行任何操作,而不必关心它是哪种具体表示。