열거 형에 Type ( "typeof ()"사용)을 저장할 수 있습니까?
그래서 저는 XNA, C # 4.0으로 게임을 만들고 있습니다. 그리고 많은 PowerUp (코드에서 모두 "PowerUp"클래스에서 상 속됨)을 관리하고 현재 가지고있는 PowerUp의 백엔드 관리를 처리해야합니다. 열거 형, PowerupEffectType, PowerUp의 각 하위 클래스에 대한 값 포함. 결국 코드에서 PowerupEffectType에서 Powerup 유형 ( Type일반적으로으로 달성 됨)으로 변환해야합니다 typeof([class name]).
이것은 그룹 프로젝트이기 때문에 가능한 한 PowerupEffectType의 각 값을 해당 클래스 Type과 결합하고 싶습니다. 즉, 다른 프로그래머가 switch 문을 사용하여 수동으로 변환을 수행하고 나중에 추가 / 확장을 확인하기를 기대하지 않습니다. 가능한 한 적은 장소에서 최소한의 변경을 포함합니다. 나는이에 대한 몇 가지 옵션을 가지고, 내가 지금까지 발견 된 것 중에 최고는 하나의 switch 문 (내가 원하는 것의 99 %) 아래로 응축 모든 것이, 몇 가지 팁 덕분에 내가 여기 발견 열거 의사 방법을 만들 수 있습니다 : HTTP : //msdn.microsoft.com/en-us/library/bb383974.aspx
하지만 한 단계 더 나아가려고합니다. a Type를 저장할 수 enum있습니까? 열거 형을 특정 유형 (링크 : http://msdn.microsoft.com/en-us/library/cc138362.aspx ) 으로 저장할 수 있지만 Type그중 하나가 아닙니다. 현재 선택 사항은 byte, sbyte, short, ushort, int, uint, long 및 ulong 입니다. 변환 Type을 위의 데이터 유형 중 하나로 저장하고 다시 저장하는 가능한 방법이 있습니까?
분명히 말해서, 이것이 제가 할 수있는 일이며, 할 방법을 찾고 있습니다.
// (Assuming 'LightningPowerup', 'FirePowerup', and 'WaterPowerup' are
// all declared classes that inherit from a single base class)
public enum PowerupEffectType
{
LIGHTNING = typeof(LightningPowerup),
FIRE = typeof(FirePowerup),
WATER = typeof(WaterPowerup)
}
이 작업을 수행 할 수있는 방법이 있습니까? 아니면 이미 99 % 완료된 문제에 대한 솔루션을 지나치게 복잡하게 만들고 있습니까?
미리 감사드립니다!
열거 형 의 값 으로 할 수는 없지만 속성에 지정할 수 있습니다 .
using System;
using System.Runtime.CompilerServices;
[AttributeUsage(AttributeTargets.Field)]
public class EffectTypeAttribute : Attribute
{
public Type Type { get; private set; }
public EffectTypeAttribute(Type type)
{
this.Type = type;
}
}
public class LightningPowerup {}
public class FirePowerup {}
public class WaterPowerup {}
public enum PowerupEffectType
{
[EffectType(typeof(LightningPowerup))]
Lightning,
[EffectType(typeof(FirePowerup))]
Fire,
[EffectType(typeof(WaterPowerup))]
Water
}
그런 다음 리플렉션을 사용하여 실행 시간에 해당 속성 값을 추출 할 수 있습니다. 그러나 저는 개인적 으로 사전을 만들 것입니다 .
private static Dictionary<PowerupEffectType, Type> EffectTypeMapping =
new Dictionary<PowerupEffectType, Type>
{
{ PowerupEffectType.Lightning, typeof(LightningPowerup) },
{ PowerupEffectType.Fire, typeof(FirePowerup) },
{ PowerupEffectType.Water, typeof(WaterPowerup) }
};
특별한 속성이 필요하지 않으며 어설픈 반사 코드로 값을 추출 할 필요가 없습니다.
이것은 정확히 당신이 요구하는 것이 아닙니다. Jon의 속성 방법이 가장 좋습니다. 그러나 확장 방법으로 포장하지 않는 이유는 무엇입니까?
public Type GetPowerupEffectType(this PowerupEffectType powerEffect)
{
switch (powerEffect)
{
case LIGHTNING:
return typeof(LightningPowerup);
case FIRE:
return typeof(FirePowerup);
case WATER:
return typeof(WaterPowerup);
default:
return default(Type);
}
}
그리고 그것을 부릅니다.
PowerupEffectType e = PowerupEffectType.WATER;
var t = e.GetPowerupEffectType();
이런 건 어때?
열거 형으로 수행하는 형식 안전성과 Type으로의 암시 적 변환을 얻습니다.
public class PowerupEffectType
{
private readonly Type _powerupType;
public static implicit operator Type(PowerupEffectType powerupEffectType)
{
return powerupEffectType._powerupType;
}
private PowerupEffectType(Type powerupType)
{
_powerupType = powerupType;
}
public static readonly PowerupEffectType LIGHTNING = new PowerupEffectType(typeof(LightningPowerup));
public static readonly PowerupEffectType FIRE = new PowerupEffectType(typeof(FirePowerup));
public static readonly PowerupEffectType WATER = new PowerupEffectType(typeof(WaterPowerup));
}
당신은을 사용할 수 있습니다 static Dictionary<PowerupEffectType, Powerup>. 나는 그것이 당신이 찾고있는 "결혼"의 종류라고 믿습니다. 쉽게 열거하고 액세스 할 수 있습니다.
You could use only numeric types as by documentation of Microsoft. By default the underlying type of each element in the enum is int. You can specify another integral numeric type by using a colon, as shown in the previous example. For a full list of possible types, see enum. Reference: Enumeration Types
Sorry, I don't quite follow this, what are you actually trying to achieve; could you give a code excerpt? I'm not sure why you can't just use inheritance here and what an enumeration gives you that type inheritance doesn't. It feels to me like you're presenting the solution rather than the problem, I may be completely wrong, could you clarify how you're planning to use this meta-information?
I'm confused, are you asking for something that tells you the type of an instance of a type/class? You can use an enumeration to store a list of the types of each type that you say, but why do you want to? You say you don't want to have the other programmers use switch statements, but I'm sorry I can't see what benefit you're getting from storing the type information in some enumeration of... the type. Every instance knows what type it is and what it can do.
What will you do with the type information? If the types all inherit from a base type, then presumably they have common functionality that can be specified in an abstract method for any special-case handling, or perhaps return a Null Object where there's nothing to do (or maybe just do nothing). This way you don't need to worry about adding new classes- as they must have the necessary behaviour. I try to avoid Enums except in situations where you're actually enumerating a fixed set of arbitrary values, they are inflexible. Enums have to be maintained, which is very difficult (in practice).
I actually think you might want to take a look at a dependency injection framework.
It looks like you are trying to have other developers work on different components and then you are trying to integrate them all at the end in one central location in the code base.
A few projects to look at:
참고URL : https://stackoverflow.com/questions/11008853/is-it-possible-to-save-a-type-using-typeof-in-an-enum
'program story' 카테고리의 다른 글
| memset () 또는 구조체를 0으로 초기화하는 값 초기화? (0) | 2020.11.30 |
|---|---|
| 아이폰 인터페이스 빌더 : Z- 인덱스, 버튼의 Z- 순서, 이미지, UI 요소 등? (0) | 2020.11.30 |
| //로 CSS 한 줄을 주석 처리하는 것은 나쁜 습관입니까? (0) | 2020.11.30 |
| 연결시 알 수없는 SSL 프로토콜 오류 (0) | 2020.11.30 |
| dplyr 필터 : 최소 변수가있는 행을 가져 오지만 최소값이 여러 개인 경우 첫 번째 행만 가져옵니다. (0) | 2020.11.30 |