How can I create an alias for a class, globally, in Unity?

为君一笑 提交于 2021-02-05 08:05:16

问题


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.

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

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

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?


回答1:


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.
}

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;
}

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.



来源:https://stackoverflow.com/questions/57341751/how-can-i-create-an-alias-for-a-class-globally-in-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!