如何在 Unity 中全局地为类创建别名? [英] How can I create an alias for a class, globally, in Unity?

查看:34
本文介绍了如何在 Unity 中全局地为类创建别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在使用字符串"来枚举角色上的设备插槽列表.我还使用字符串"来枚举该物品可以装备的类类型.

Right now, I am using "string" to enumerate a list of equipment slots on a character. I am also using "string" to enumerate the class type that the item can be equipped on.

这使得我获取、删除、生成等项目的所有方法都涉及两个字符串参数,即设备插槽和类类型.

This makes all my methods where I get, remove, generate, etc. items involve having two string parameters that is an equipment slot and class type.

我真正想要的是使用 2 个类,以便为 slot 和 class_type 提供 2 个强类型概念.

What I really would like is to use 2 classes so that I have 2 strongly typed concepts for the slot and class_type.

问题是 string 是一个密封类,因此我无法扩展它!

The problem is that string is a sealed class and thus I cannot extend it!

我想到的一个解决方案是使用使用 SlotType = string;"作为别名,但我不知道如何在全球范围内开展这项工作.

A solution I conceived is to use "using SlotType = string;" as alias but I don't know how to have this work GLOBALLY.

如何为类定义全局别名?

How do you define a global alias for a class?

推荐答案

在 C# 中,您可以使用using"创建类型别名.因为显然该术语在 C# 中需要第三种含义 ;) 但是using 指令的范围仅限于它出现的文件.",因此它不会全局应用.

In C# you can create a type alias using "using". Because obviously that term needed a 3rd meanings in C# ;) However 'the scope of a using directive is limited to the file in which it appears.', so it would not apply globally.

还有另一种选择——创建一个子类.例如,

There is another option - create a subclass. For example,

public class ListOfIntegers : List<int>{
  //Nothing to do here.
}

会给你一个 List 的分类别名,它适用于 ListOfIntegers 作为项目参考给出的任何地方.

would give you a sort-off-alias for List<int> that applies everywhere ListOfIntegers is given as Project Reference.

至于不能扩展的东西:封装起来就好了.

As for not being able to extend something: Just encapsulate it instead.

public class TypedString1 {
  public value;
}

public class TypedString2 {
  public value;
}

但是您可能希望设置它以便将字符串重载用于诸如 Equality 和 ToString 调用之类的东西.也可能隐式转换为字符串以使其更易于使用.

But you may want to set it up so that string overloads are used for stuff like Equality and ToString calls. Also propably a implicit cast to string to make it easier to use.

这篇关于如何在 Unity 中全局地为类创建别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆