Skip to content

Instantly share code, notes, and snippets.

@overing
Last active October 26, 2023 09:27
Show Gist options
  • Save overing/36c8f0fed2f96b3dabdb9da98434391a to your computer and use it in GitHub Desktop.
Save overing/36c8f0fed2f96b3dabdb9da98434391a to your computer and use it in GitHub Desktop.
取得有效的 BuildTargetGroup 替代名稱
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using UnityEditor;
public sealed class EnumTest
{
[Test]
[TestCase("iOS", true, "iOS")] // iOS 有效
[TestCase("iPhone", true, "iOS")] // iPhone 已棄用但有替代名稱 iOS
[TestCase("PS3", false, null)] // PS3 已棄用且沒替代名稱
public void TestTryGetAvailableName(string name, bool available, string altName)
{
var enumValue = Enum.Parse<BuildTargetGroup>(name);
Assert.AreEqual(available, enumValue.TryGetAvailableName(out var availableName));
Assert.AreEqual(altName, availableName);
}
}
public static class BuildTargetGroupExtensions
{
static readonly Dictionary<string, (bool deprecated, BuildTargetGroup value)> s_name2Available;
static BuildTargetGroupExtensions()
{
var buildTargetGroupType = typeof(BuildTargetGroup);
var obsoleteAttributeType = typeof(ObsoleteAttribute);
s_name2Available = Enum.GetNames(buildTargetGroupType)
.ToDictionary(name => name, name =>
{
var deprecated = Attribute.IsDefined(buildTargetGroupType.GetField(name), obsoleteAttributeType);
var value = Enum.Parse<BuildTargetGroup>(name);
return (deprecated, value);
});
}
/// <summary>
/// 嘗試取得有效的替代名稱 (排除已由 <see cref="ObsoleteAttribute" /> 標註為棄用的部分)
/// </summary>
/// <param name="name">有效的替代名稱, 如果沒有傳回 null</param>
/// <returns>傳入的 <paramref name="buildTarget"/> 如果有任何有效的名稱或替代名稱</returns>
public static bool TryGetAvailableName(this BuildTargetGroup buildTarget, out string name)
{
name = buildTarget.ToString();
if (!s_name2Available.TryGetValue(name, out var meta))
{
name = null;
return false;
}
var alt = s_name2Available.FirstOrDefault(p => p.Value.value == buildTarget && !p.Value.deprecated);
if (string.IsNullOrEmpty(alt.Key))
{
name = null;
return false;
}
name = alt.Key;
return true;
}
}
@overing
Copy link
Author

overing commented Oct 26, 2023

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment