我希望能够向用户提供一个选择-是使用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语句,这是可能的吗?
谢谢
发布于 2013-07-15 02:03:55
您可以使用接口和工厂,如下所示:
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做任何事情,而不必关心它是哪种具体的表示。
发布于 2013-07-15 01:49:08
看起来你可以使用一个泛型来做这个:
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();https://stackoverflow.com/questions/17641713
复制相似问题