首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >条件类型别名

条件类型别名
EN

Stack Overflow用户
提问于 2013-07-15 01:17:15
回答 2查看 251关注 0票数 2

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

代码语言:javascript
复制
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语句,这是可能的吗?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-15 02:03:55

您可以使用接口和工厂,如下所示:

代码语言:javascript
复制
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做任何事情,而不必关心它是哪种具体的表示。

票数 1
EN

Stack Overflow用户

发布于 2013-07-15 01:49:08

看起来你可以使用一个泛型来做这个:

代码语言:javascript
复制
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>();
        }
    }
}

并创建一个:

代码语言:javascript
复制
if (is16Bit)
    return Conditional<short>.Create();
else
    return Conditional<int>.Create();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17641713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档