编程语言
首页 > 编程语言> > c# – 具有明确类型安全分类的泛型类

c# – 具有明确类型安全分类的泛型类

作者:互联网

我正在寻找一种方法来创建一个通用基类,它具有使用内部属性的类型安全分类.
为了清楚起见,该类不必使用泛型语言功能,只要它是通用的,我正在寻找具有编译时类型安全性的东西.

作为一个例子,这里是一个简单的分类法,我想用同一个类的多个实例来表示

Wood
  Crate
  Box
Metal
  Crate
  Bar

其中的排列是

Wood Crate
Wood Box
Metal Crate
Metal Bar

最初我虽然可以使用枚举来表示不同级别的分类法

public enum EFirstLevel
{
    Wood,
    Metal
}

public enum ESecondLevel
{
    Crate,
    Box,
    Bar
}


public class BaseItem
{
    EFirstLevel FirstLevel;
    ESecondLevel SecondLevel;

    public BaseItem(EFirstLevel aFirst, ESecondLevel aSecond)
    {
        FirstLevel = aFirst;
        SecondLevel = aSecond;
    }
}

我可以用以下方法创建上面的项目:

var item1 = new BaseItem(EFirstLevel.Wood,ESecondLevel.Crate)
var item2 = new BaseItem(EFirstLevel.Wood,ESecondLevel.Box)
var item3 = new BaseItem(EFirstLevel.Metal,ESecondLevel.Crate)
var item4 = new BaseItem(EFirstLevel.Metal,ESecondLevel.Bar)

但我也可以创造

var item5 = new BaseItem(EFirstLevel.Wood,ESecondLevel.Bar)

这对我来说是不正确的.

你们是否知道一种模式可以让我创建一个单独的类来以类型安全的方式表示示例分类,禁止创建错误的组合.

它还需要适用于N级分类,上面的2个级别只是一个例子.

谢谢

更新:
我确实需要编译时类型安全.
我可以使用继承很容易地使用多个类来实现这一点,我试图找到一个只使用单个基类的实例的解决方案.

如果您需要更多信息,请告诉我

更新:
@Maarten是的,我正在努力确保维护层次结构,因此如果EFirstLevel为1,那么ESecondLevel必须是Crate或Box.

只是为了肯定我很高兴有其他支持类,我想避免的是必须为每个分类学价值明确创建一个类.

我正在努力实现的是提供一个类的示例布局,它保持了这种分类型安全性,因此我可以反思它并置换组合.在保持类型安全的同时,我需要一般地实例化所述排列.

我可能反映的课程可能来自第三方,因此我可能事先不知道每个级别的值.
我可以将所有可能的组合生成到一组具有类型安全内部枚举的类中,但是这需要在您更改任何级别的项目时重新生成所述类.
我只是想知道是否有一个实现我的目标而不必生成任何课程.

编辑:将此部分移至答案

解决方法:

我认为你不会在没有创建类/接口的情况下逃脱,并且编译时检查该对象是否符合你的分类.

我建议解决方案如下:

// Define the taxonomic levels here. Each level (except the first) references its next-higher taxonomic level in a type constraint
interface Material { }
interface Object<TMaterial> where TMaterial : Material { }

// Define the items in the highest taxonomic level (materials)
interface Wood : Material { }
interface Metal : Material { }

// Define the items in the 2nd taxonomic level (objects), implementing the appropriate interfaces to specify what the valid top-level taxonomies it can fall under.
interface Crate : Object<Wood>, Object<Metal> { }
interface Bar : Object<Metal> { }
interface Box : Object<Wood> { }

// Define an item class with type constraints to ensure the taxonomy is correct
abstract class Item<TMaterial, TObject>
    where TMaterial : Material
    where TObject : Object<TMaterial>
{
}

通过上面定义,我们现在可以定义有效的项目:

class MetalBar : Item<Metal, Bar> { }
class MetalCrate : Item<Metal, Crate> { }
class WoodCrate : Item<Wood, Crate> { }
class WoodBox : Item<Wood, Box> { }

但是,尝试创建无效项(例如木条)会导致编译时错误:

class WoodBar : Item<Wood, Bar> { }

The type ‘Taxonomy.Bar’ cannot be used as type parameter ‘TObject’ in the generic type or method ‘Taxonomy.Item’. There is no implicit reference conversion from ‘Taxonomy.Bar’ to ‘Taxonomy.Object’

标签:c,type-safety,generics,taxonomy
来源: https://codeday.me/bug/20190624/1282849.html