Here are the examples of the csharp api System.Enum.GetNames(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1027 Examples
19
Source : TableCompiler.Placeholders.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public IEnumerable<PlaceholderContainer> GetPlaceholders(
bool inSimulation = false,
bool forTimeline = false)
{
var placeholders = default(IEnumerable<PlaceholderContainer>);
lock (this.PlaceholderListSyncRoot)
{
placeholders = new List<PlaceholderContainer>(this.placeholderList);
}
// Simulationモードでなければ抜ける
if (!inSimulation)
{
if (forTimeline)
{
placeholders = placeholders.Select(x =>
new PlaceholderContainer(
x.Placeholder
.Replace("<", "[")
.Replace(">", "]"),
x.ReplaceString,
x.Type));
}
return placeholders;
}
// プレースホルダ生成用のメソッド
string createPH(string name) => !forTimeline ? $"<{name}>" : $"[{name}]";
// シミュレータ向けプレースホルダのリストを生成する
var placeholdersInSim = new List<PlaceholderContainer>(placeholders);
#if DEBUG
placeholdersInSim.Clear();
#endif
// 汎用プレースホルダ
var idsInSim = new[]
{
new PlaceholderContainer(createPH("id"), @"([0-9a-fA-F]+|<id>|\[id\]|<id4>|\[id4\]|<id8>|\[id8\])", PlaceholderTypes.Custom),
new PlaceholderContainer(createPH("id4"), @"([0-9a-fA-F]{4}|<id4>|\[id4\])", PlaceholderTypes.Custom),
new PlaceholderContainer(createPH("id8"), @"([0-9a-fA-F]{8}|<id8>|\[id8\])", PlaceholderTypes.Custom),
new PlaceholderContainer(createPH("_duration"), @"(?<_duration>[\d\.]+)", PlaceholderTypes.Custom),
new PlaceholderContainer(createPH("job"), $"(?<_job>{string.Join("|", GetJobNames())})" , PlaceholderTypes.Custom)
};
var jobs = Enum.GetNames(typeof(JobIDs));
var jobsPlacement = string.Join("|", jobs.Select(x => $@"\[{x}\]"));
// JOB系プレースホルダ
var jobsInSim = new List<PlaceholderContainer>();
foreach (var job in jobs)
{
jobsInSim.Add(new PlaceholderContainer(createPH(job), $@"\[{job}\]", PlaceholderTypes.Party));
}
// PC系プレースホルダ
var pcInSim = new[]
{
new PlaceholderContainer(createPH("mex"), @"(?<_mex>\[mex\])", PlaceholderTypes.Me),
new PlaceholderContainer(createPH("nex"), $@"(?<_nex>{jobsPlacement}|\[nex\])", PlaceholderTypes.Party),
new PlaceholderContainer(createPH("pc"), $@"(?<_pc>{jobsPlacement}|\[pc\]|\[mex\]|\[nex\])", PlaceholderTypes.Party),
};
// ID系を置き換える
foreach (var ph in idsInSim)
{
var old = placeholdersInSim.FirstOrDefault(x => x.Placeholder == ph.Placeholder);
if (old != null)
{
old.ReplaceString = ph.ReplaceString;
}
else
{
placeholdersInSim.Add(ph);
}
}
// JOB系を追加する
foreach (var ph in jobsInSim)
{
var old = placeholdersInSim.FirstOrDefault(x => x.Placeholder == ph.Placeholder);
if (old != null)
{
// NO-OP
}
else
{
placeholdersInSim.Add(ph);
}
}
// PC系を追加する
foreach (var ph in pcInSim)
{
var old = placeholdersInSim.FirstOrDefault(x => x.Placeholder == ph.Placeholder);
if (old != null)
{
// NO-OP
}
else
{
placeholdersInSim.Add(ph);
}
}
return placeholdersInSim;
}
19
Source : Config.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private static void MigrateConfig(
string file)
{
var buffer = new StringBuilder();
buffer.Append(File.ReadAllText(file, new UTF8Encoding(false)));
var xdoc = XDoreplacedent.Parse(buffer.ToString());
var xelements = xdoc.Root.Elements();
if (xelements.Any(x => x.Name == nameof(GlobalLogFilters)))
{
var filtersParent = xelements
.FirstOrDefault(x => x.Name == nameof(GlobalLogFilters));
var filters = filtersParent.Elements();
var typeNames = Enum.GetNames(typeof(LogMessageType));
// 消滅したLogTypeを削除する
var toRemove = filters
.Where(x => !typeNames.Contains(x.Attribute("Key").Value))
.ToArray();
foreach (var e in toRemove)
{
e.Remove();
}
// 新しく増えたLogTypeを追加する
var toAdd = typeNames
.Where(x => !filters.Any(y => y.Attribute("Key").Value == x));
foreach (var key in toAdd)
{
var e = new XElement("Filter");
e.SetAttributeValue("Key", key);
e.SetAttributeValue("Value", false);
filtersParent.Add(e);
}
}
File.WriteAllText(file, xdoc.ToString(), new UTF8Encoding(false));
}
19
Source : PropertyViewModelFactory.cs
with GNU General Public License v3.0
from AnyStatus
with GNU General Public License v3.0
from AnyStatus
public IPropertyViewModel Create(object source, PropertyInfo propertyInfo, IEnumerable<IPropertyViewModel> properties)
{
if (Attribute.IsDefined(propertyInfo, typeof(EndpointSourceAttribute)))
{
var attribute = propertyInfo.GetCustomAttribute<ItemsSourceAttribute>();
return _serviceProvider.GetService(attribute.Type) is IItemsSource itemsSource ?
new EndpointPropertyViewModel(_mediator, _context, propertyInfo, source, itemsSource, properties, attribute.Autoload) :
null;
}
if (Attribute.IsDefined(propertyInfo, typeof(ItemsSourceAttribute)))
{
var attribute = propertyInfo.GetCustomAttribute<ItemsSourceAttribute>();
return _serviceProvider.GetService(attribute.Type) is IItemsSource itemsSource ?
new DropDownPropertyViewModel(propertyInfo, source, itemsSource, properties, attribute.Autoload) :
null;
}
if (Attribute.IsDefined(propertyInfo, typeof(AsyncItemsSourceAttribute)))
{
var attribute = propertyInfo.GetCustomAttribute<AsyncItemsSourceAttribute>();
return _serviceProvider.GetService(attribute.Type) is IAsyncItemsSource asyncItemsSource ?
new DropDownPropertyViewModel(propertyInfo, source, asyncItemsSource, properties, attribute.Autoload) :
null;
}
if (propertyInfo.PropertyType.IsEnum)
{
return new DropDownPropertyViewModel(propertyInfo, source, Enum.GetNames(propertyInfo.PropertyType).Select(i => new NameValueItem(i, i)));
}
if (propertyInfo.PropertyType == typeof(string))
{
var vm = new TextPropertyViewModel(propertyInfo, source);
var attribute = propertyInfo.GetCustomAttribute<TextAttribute>();
if (attribute is not null)
{
vm.Wrap = attribute.Wrap;
vm.AcceptReturns = attribute.AcceptReturns;
}
return vm;
}
if (propertyInfo.PropertyType == typeof(bool))
{
return new BooleanPropertyViewModel(propertyInfo, source);
}
if (propertyInfo.PropertyType.IsNumeric())
{
return new NumericPropertyViewModel(propertyInfo, source);
}
return null;
}
19
Source : ImageTrackingExample.cs
with MIT License
from aornelas
with MIT License
from aornelas
private void HandleOnButtonDown(byte controllerId, MLInputControllerButton button)
{
if (_controllerConnectionHandler.IsControllerValid(controllerId) && button == MLInputControllerButton.Bumper)
{
_viewMode = (ViewMode)((int)(_viewMode + 1) % Enum.GetNames(typeof(ViewMode)).Length);
_viewModeLabel.text = string.Format("View Mode: {0}", _viewMode.ToString());
}
UpdateVisualizers();
}
19
Source : SecureTransportContext.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private X509Certificate2Collection LoadClientCertificates()
{
X509Certificate2Collection certificates = new X509Certificate2Collection();
if(!String.IsNullOrWhiteSpace(this.ClientCertFileName))
{
Tracer.DebugFormat("Attempting to load Client Certificate file: {0}", this.ClientCertFileName);
X509Certificate2 certificate = new X509Certificate2(this.ClientCertFileName, this.ClientCertPreplacedword);
Tracer.DebugFormat("Loaded Client Certificate: {0}", certificate.Subject);
certificates.Add(certificate);
}
else
{
string storeName = String.IsNullOrWhiteSpace(this.KeyStoreName) ? StoreName.My.ToString() : this.KeyStoreName;
StoreLocation storeLocation = StoreLocation.CurrentUser;
if(!String.IsNullOrWhiteSpace(this.KeyStoreLocation))
{
bool found = false;
foreach(string location in Enum.GetNames(typeof(StoreLocation)))
{
if(String.Compare(this.KeyStoreLocation, location, true) == 0)
{
storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), location, true);
found = true;
break;
}
}
if (!found)
{
throw new NMSException(string.Format("Invalid Store location {0}", this.KeyStoreLocation), NMSErrorCode.PROPERTY_ERROR);
}
}
Tracer.DebugFormat("Loading store {0}, from location {1}.", storeName, storeLocation.ToString());
try
{
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
X509Certificate2[] storeCertificates = new X509Certificate2[store.Certificates.Count];
store.Certificates.CopyTo(storeCertificates, 0);
certificates.AddRange(storeCertificates);
}
catch(Exception ex)
{
Tracer.WarnFormat("Error loading KeyStore, name : {0}; location : {1}. Cause {2}", storeName, storeLocation, ex);
throw ExceptionSupport.Wrap(ex, "Error loading KeyStore.", storeName, storeLocation.ToString());
}
}
return certificates;
}
19
Source : AttributesUtilityWindow.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
private void OnEnable()
{
_lastEntry = -1;
if (AttributesMaster.attributesEnabled)
{
var vals = Enum.GetValues(AttributesMaster.attributesEnumType);
var names = Enum.GetNames(AttributesMaster.attributesEnumType);
int idx = 0;
foreach (int v in vals)
{
var val = Math.Abs((long)v);
if (val > 0)
{
_lastEntry = (int)Math.Log(val, 2);
_entries[_lastEntry] = names[idx];
}
idx++;
}
_fileLocation = LocateAttributeFile();
}
}
19
Source : BaseEndpointClientTests.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
protected void replacedertJsonValue(JsonElement expected, object actual)
{
bool switched = true;
switch (actual)
{
case Guid guid:
replacedert.Equal(new Guid(expected.GetString()), guid);
break;
case DateTime dateTime:
replacedert.Equal(expected.GetDateTime(), dateTime);
break;
case DateTimeOffset dateTime:
replacedert.Equal(expected.GetDateTimeOffset(), dateTime);
break;
case TimeSpan timeSpan:
replacedert.Equal(TimeSpan.FromSeconds(expected.GetInt32()), timeSpan);
break;
case int @int:
if (expected.ValueKind == JsonValueKind.String)
replacedert.Equal(int.Parse(expected.GetString()), @int);
else
replacedert.Equal(expected.GetInt32(), @int);
break;
case long @long:
if (expected.ValueKind == JsonValueKind.String)
replacedert.Equal(long.Parse(expected.GetString()), @long);
else
replacedert.Equal(expected.GetInt64(), @long);
break;
case double @double:
replacedert.Equal(expected.GetDouble(), @double, 10);
break;
case bool @bool:
replacedert.Equal(expected.GetBoolean(), @bool);
break;
case string @string:
replacedert.Equal(expected.GetString(), @string);
break;
case null:
if (expected.ValueKind == JsonValueKind.String)
replacedert.Equal(expected.GetString(), string.Empty);
break;
default:
switched = false;
break;
}
if (!switched)
{
var type = actual!.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ApiEnum<>))
{
var enumType = type.GenericTypeArguments[0];
dynamic @enum = actual; // Just for easiness
replacedert.Equal(expected.GetString(), @enum.RawValue);
if (@enum.IsUnknown)
{
var enumNames = Enum.GetNames(enumType)
.Select(x => enumType.GetField(x).GetCustomAttribute<EnumMemberAttribute>()?.Value ?? x);
replacedert.True(enumNames.Contains((string)@enum.RawValue, StringComparer.OrdinalIgnoreCase), $"Expected '{expected}' to be a value in enumerator {@enum.Value.GetType().FullName}; detected value '{@enum.Value}'");
}
dynamic expectedEnum = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new[] { expected.GetString() }, null);
replacedert.Equal(expectedEnum.Value, @enum.Value);
switched = true;
}
}
if (!switched)
replacedert.Equal(expected.GetString(), actual!.ToString());
}
19
Source : EnumController.cs
with GNU General Public License v3.0
from arduosoft
with GNU General Public License v3.0
from arduosoft
[HttpGet("{name}")]
public RestMessage<Dictionary<string, string>> Get(string name)
{
var data = new Dictionary<string, string>();
var result = new RestMessage<Dictionary<string, string>>(data);
try
{
var values = Enum.GetValues(enumMap[name]);
var names = Enum.GetNames(enumMap[name]);
for (int i = 0; i < names.Length; i++)
{
data[names[i]] = values.GetValue(i).ToString();
}
}
catch (Exception err)
{
this.logger.LogError(err, "error during enum resolution");
result.Errors.Add(new Error()
{
Code = "001",
replacedle = "Error getting enum",
Description = err.Message
});
}
return result;
}
19
Source : FileRepository.cs
with MIT License
from Arefu
with MIT License
from Arefu
public List<string> GetSupportedFileTypes()
{
return Enum.GetNames(typeof(Constants.SupportedImageType)).ToList();
}
19
Source : EnumTogglesAttributeDrawer.cs
with MIT License
from arimger
with MIT License
from arimger
public virtual void Prepare(Type enumType)
{
if (cachedEnumDatas.TryGetValue(enumType, out var data))
{
enumData = data;
return;
}
var rawLabels = Enum.GetNames(enumType);
var rawValues = Enum.GetValues(enumType);
enumData = cachedEnumDatas[enumType] = GetEnumData(rawLabels, rawValues);
}
19
Source : Character.cs
with GNU General Public License v3.0
from arycama
with GNU General Public License v3.0
from arycama
public void Initialize(NpcRecord npcRecord)
{
this.npcData = npcRecord;
if(npcRecord.Faction != null)
{
Factions.Add(npcRecord.Faction, new FactionRankReputationPair(npcRecord.NpcSubData.Rank, 0));
}
// Initialize various things
attributeMods = new byte[Enum.GetNames(typeof(CharacterAttribute)).Length];
skillMods = new byte[Enum.GetNames(typeof(CharacterSkill)).Length];
spells = new List<SpellRecord>(npcRecord.Spells);
fatigue = MaxFatigue;
health = MaxHealth;
magicka = MaxMagicka;
}
19
Source : ObjectStore.cs
with GNU General Public License v3.0
from askeladdk
with GNU General Public License v3.0
from askeladdk
private void LoadLands(IConfiguration cfg)
{
var landTypes = Enum.GetNames(typeof(LandType));
var speedTypes = Enum.GetNames(typeof(SpeedType));
for(var i = 0; i < landTypes.Length; i++)
{
var buildable = cfg.GetBool(landTypes[i], "Buildable");
var speedMultipliers = new float[Speed.Count];
for(var j = 0; j < speedTypes.Length; j++)
speedMultipliers[j] = cfg.GetFloat(landTypes[i], speedTypes[j]);
this.lands[i] = new Land(buildable, speedMultipliers);
}
}
19
Source : ObjectStore.cs
with GNU General Public License v3.0
from askeladdk
with GNU General Public License v3.0
from askeladdk
private void LoadSequences(IConfiguration cfg)
{
var enumNames = Enum.GetNames(typeof(SequenceType));
foreach(var kv in cfg.Enumerate("Sequences"))
{
var id = kv.Value;
var seq = new Sequence();
foreach(var name in enumNames)
{
if(!cfg.Contains(id, name))
continue;
var a = cfg.GetIntArray(id, name, 5);
if(a == null)
continue;
var seqe = new SequenceEntry(a[0], a[1], a[2], a[3], a[4]);
var seqt = Enum.Parse<SequenceType>(name);
seq.Set(seqt, seqe);
}
sequences[id] = seq;
}
}
19
Source : LocalizationExporter.cs
with MIT License
from Auros
with MIT License
from Auros
public void DumpBaseGameLocalization()
{
string filePath = Path.Combine(UnityGame.InstallPath, "localization.csv");
int numberOfLanguages = Enum.GetNames(typeof(Locale)).Length - 2; // don't include Locale.None and Locale.English
string commas = new string(',', numberOfLanguages);
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
Localizationreplacedet baseGamereplacedet = Localization.Instance.InputFiles.First();
List<List<string>> rows = CsvReader.Parse(baseGamereplacedet.Textreplacedet.text);
writer.WriteLine("Polyglot,100," + commas);
foreach (List<string> row in rows.SkipWhile(r => r[0] != "Polyglot").Skip(1))
{
if (string.IsNullOrEmpty(row[0]) || kLocalizationKeyIgnoreList.Contains(row[0])) continue;
string key = row.ElementAtOrDefault(0);
string context = row.ElementAtOrDefault(1);
string english = row.ElementAtOrDefault(2)?.TrimEnd();
if (kCorrections.TryGetValue(key, out var rule))
{
if (!english.Contains(rule.find)) Plugin.Log.Warn($"Rule for '{key}' ('{rule.find}' -> '{rule.replace}') won't do anything on '{english}'");
english = english.Replace(rule.find, rule.replace);
}
writer.WriteLine($"{EscapeCsvValue(key)},{EscapeCsvValue(context)},{EscapeCsvValue(english)}" + commas);
}
foreach ((string key, string value) in kAdditionalKeys)
{
writer.WriteLine($"{EscapeCsvValue(key)},,{EscapeCsvValue(value)}" + commas);
}
}
}
catch (Exception ex)
{
Plugin.Log.Error("Could not dump base game localization: " + ex);
}
}
19
Source : DynamicJsonResponse.cs
with Apache License 2.0
from Autodesk-Forge
with Apache License 2.0
from Autodesk-Forge
public static T ToEnum<T> (string str) {
var enumType =typeof (T) ;
foreach ( var name in Enum.GetNames (enumType) ) {
var enumMemberAttribute =((EnumMemberAttribute [])enumType.GetField (name).GetCustomAttributes (typeof (EnumMemberAttribute), true)).Single () ;
if ( enumMemberAttribute.Value == str )
return ((T)Enum.Parse (enumType, name)) ;
}
//throw exception or whatever handling you want or
return (default (T)) ;
}
19
Source : EnumExtensions.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
public static T GetEnumByResourceValue<T>(string value, ResourceSet resourceSet) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("value must be of Enum type", value);
}
var resourceKeys = resourceSet.Cast<DictionaryEntry>()
.Where(item => item.Value.ToString().ToLower() == value.ToLower()).ToList();
var entries = resourceKeys.Where(k => Enum.GetNames(typeof(T)).Contains(k.Key));
if (entries.Any())
{
return (T) Enum.Parse(typeof(T), (string) entries.First().Key);
}
throw new KeyNotFoundException(string.Format("value {0} for Enum {1}, not exists in resources ", value, typeof(T)));
}
19
Source : Get-EC2InstanceMetadata-Cmdlet.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
void EnumerateRecognizedCategories()
{
WriteObject(Enum.GetNames(typeof(MetadataCategory)), true);
}
19
Source : WindowsSourceFactory.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public ISource CreateInstance(string entry, IPlugInContext context)
{
var config = context.Configuration;
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException($"Source type '{entry}' is only supported on Windows");
}
switch (entry.ToLowerInvariant())
{
case WINDOWS_EVENT_LOG_POLLING_SOURCE:
var pollingOptions = new WindowsEventLogPollingSourceOptions();
ParseWindowsEventLogSourceOptions(config, pollingOptions);
ParseEventLogPollingSourceOptions(config, pollingOptions);
var weps = new WindowsEventPollingSource(config[ConfigConstants.ID],
config["LogName"], config["Query"], context.BookmarkManager, pollingOptions, context);
return weps;
case WINDOWS_EVENT_LOG_SOURCE:
var eventOpts = new WindowsEventLogSourceOptions();
ParseWindowsEventLogSourceOptions(config, eventOpts);
var source = new EventLogSource(config[ConfigConstants.ID], config["LogName"], config["Query"],
context.BookmarkManager, eventOpts, context);
return source;
case WINDOWS_PERFORMANCE_COUNTER_SOURCE:
var performanceCounterSource = new PerformanceCounterSource(context);
return performanceCounterSource;
case WINDOWS_ETW_EVENT_SOURCE:
var providerName = config["ProviderName"];
var traceLevelString = DefaultMissingConfig(config["TraceLevel"], "Verbose");
var matchAnyKeywordString = DefaultMissingConfig(config["MatchAnyKeyword"], ulong.MaxValue.ToString());
if (string.IsNullOrWhiteSpace(providerName))
{
throw new Exception($"A provider name must be specified for the WindowsEtwEventSource.");
}
TraceEventLevel traceLevel;
ulong matchAnyKeyword;
if (!Enum.TryParse<TraceEventLevel>(traceLevelString, out traceLevel))
{
var validNames = string.Join(", ", Enum.GetNames(typeof(TraceEventLevel)));
throw new Exception($"{traceLevelString} is not a valid trace level value ({validNames}) for the WindowsEtwEventSource.");
}
matchAnyKeyword = ParseMatchAnyKeyword(matchAnyKeywordString);
var eventSource = new EtwEventSource(providerName, traceLevel, matchAnyKeyword, context);
return eventSource;
default:
throw new Exception($"Source type {entry} not recognized.");
}
}
19
Source : SelectListItemNoNotify.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static IList<SelectLisreplacedem> ToSelectListByDesc(
Type enumType
, string firstText = "请选择"
, string firstValue = "-1"
)
{
IList<SelectLisreplacedem> lisreplacedem = new List<SelectLisreplacedem>();
if (enumType.IsEnum)
{
AddFirst(lisreplacedem, firstText, firstValue);
string[] names = Enum.GetNames(enumType);
names.ToList().ForEach(item =>
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组
description = arr != null && arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : item; //属性描述
lisreplacedem.Add(new SelectLisreplacedem() { Value = ((int)Enum.Parse(enumType, item)).ToString(), Text = description });
});
}
else
{
throw new ArgumentException("请传入正确的枚举!");
}
return lisreplacedem;
}
19
Source : SelectListItemNoNotify.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static IList<SelectLisreplacedem> ToSelectListByDesc(
Type enumType
)
{
IList<SelectLisreplacedem> lisreplacedem = new List<SelectLisreplacedem>();
if (enumType.IsEnum)
{
string[] names = Enum.GetNames(enumType);
names.ToList().ForEach(item =>
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组
description = arr != null && arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : item; //属性描述
lisreplacedem.Add(new SelectLisreplacedem() { Value = ((int)Enum.Parse(enumType, item)).ToString(), Text = description });
});
}
else
{
throw new ArgumentException("请传入正确的枚举!");
}
return lisreplacedem;
}
19
Source : SelectListItemNoNotify.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static IList<SelectLisreplacedemNoNotify> ToSelectListNoNotifyByDesc(
Type enumType
)
{
IList<SelectLisreplacedemNoNotify> lisreplacedem = new List<SelectLisreplacedemNoNotify>();
if (enumType.IsEnum)
{
string[] names = Enum.GetNames(enumType);
names.ToList().ForEach(item =>
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组
description = arr != null && arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : item; //属性描述
lisreplacedem.Add(new SelectLisreplacedemNoNotify() { Value = ((int)Enum.Parse(enumType, item)).ToString(), Text = description });
});
}
else
{
throw new ArgumentException("请传入正确的枚举!");
}
return lisreplacedem;
}
19
Source : SelectListItemNoNotify.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static IList<SelectLisreplacedemNoNotify> ToSelectListNoNotifyByDesc(
Type enumType
, string firstText = "请选择"
, string firstValue = "-1"
)
{
IList<SelectLisreplacedemNoNotify> lisreplacedem = new List<SelectLisreplacedemNoNotify>();
if (enumType.IsEnum)
{
AddFirst(lisreplacedem, firstText, firstValue);
string[] names = Enum.GetNames(enumType);
names.ToList().ForEach(item =>
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组
description = arr != null && arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : item; //属性描述
lisreplacedem.Add(new SelectLisreplacedemNoNotify() { Value = ((int)Enum.Parse(enumType, item)).ToString(), Text = description });
});
}
else
{
throw new ArgumentException("请传入正确的枚举!");
}
return lisreplacedem;
}
19
Source : Weight.cs
with MIT License
from azist
with MIT License
from azist
private static void getPair(string val, out string valueString, out string unitString)
{
valueString = null;
unitString = null;
const string VALUE_ENDS = "0123456789 ";
string normString = val.Trim().ToUpper();
foreach (string unitName in Enum.GetNames(typeof(UnitType)))
{
int idx = normString.IndexOf(unitName.ToUpper()); // we search case-insensitive
if (idx == normString.Length - unitName.Length // search unit name at the end of string
&& VALUE_ENDS.IndexOf(normString[idx - 1]) >= 0) // left part (value) should ends with VALUE_ENDS char
{
valueString = normString.Substring(0, idx).Trim();
unitString = unitName;
return;
}
}
}
19
Source : Instrumentation.cs
with MIT License
from azist
with MIT License
from azist
private JsonDataMap getComponentMap(IApplicationComponent cmp, string group = null)
{
var cmpMap = new JsonDataMap();
var parameterized = cmp as IExternallyParameterized;
var instrumentable = cmp as IInstrumentable;
cmpMap["instrumentable"] = instrumentable != null;
cmpMap["instrumentationEnabled"] = instrumentable != null ? instrumentable.InstrumentationEnabled : false;
cmpMap["SID"] = cmp.ComponentSID;
cmpMap["startTime"] = Azos.Apps.Terminal.Cmdlets.App.DetailedComponentDateTime( cmp.ComponentStartTime );
cmpMap["tp"] = cmp.GetType().FullName;
if (cmp.ComponentCommonName.IsNotNullOrWhiteSpace()) cmpMap["commonName"] = cmp.ComponentCommonName;
if (cmp is INamed) cmpMap["name"] = ((INamed)cmp).Name;
if (cmp.ComponentDirector != null) cmpMap["director"] = cmp.ComponentDirector.GetType().FullName;
if (parameterized == null) return cmpMap;
var pars = group.IsNotNullOrWhiteSpace() ? parameterized.ExternalParametersForGroups(group) : parameterized.ExternalParameters;
if (pars == null) return cmpMap;
pars = pars.Where(p => p.Key != "InstrumentationEnabled").OrderBy(p => p.Key);
if (pars.Count() == 0) return cmpMap;
var parameters = new List<JsonDataMap>();
foreach(var par in pars)
{
object val;
if (!parameterized.ExternalGetParameter(par.Key, out val)) continue;
var parameterMap = new JsonDataMap();
string[] plist = null;
var tp = par.Value;
if (tp == typeof(bool)) plist = new string[] { "true", "false" };
else if (tp.IsEnum) plist = Enum.GetNames(tp);
parameterMap["key"] = par.Key;
parameterMap["plist"] = plist;
var valStr = val.replacedtring();
if (valStr.IsNotNullOrWhiteSpace() && valStr.StartsWith(CoreConsts.EXT_PARAM_CONTENT_LACONIC))
{
valStr = valStr.Substring(Azos.CoreConsts.EXT_PARAM_CONTENT_LACONIC.Length);
parameterMap["val"] = valStr.AsLaconicConfig().ToJSONDataMap();
// parameterMap["val"] = @" {
// 'detailed-instrumentation': true,
// tables:
// {
// master: { name: 'tfactory', 'fields-qty': 14},
// slave: { name: 'tdoor', 'fields-qty': 20, important: true}
// },
// tables1:
// {
// master: { name: 'tfactory', 'fields-qty': 14},
// slave: { name: 'tdoor', 'fields-qty': 20, important: true}
// },
// tables2:
// {
// master: { name: 'tfactory', 'fields-qty': 14},
// slave: { name: 'tdoor', 'fields-qty': 20, important: true}
// }
// }".JSONToDataObject();
parameterMap["ct"] = "obj"; // content type is object (string in JSON format)
}
else
{
parameterMap["val"] = val;
parameterMap["ct"] = "reg"; // content type is regular
}
parameters.Add(parameterMap);
}
cmpMap["params"] = parameters;
return cmpMap;
}
19
Source : Instrumentation.cs
with MIT License
from azist
with MIT License
from azist
[Action]
public object LoadComponents(string group = null)
{
var components = App.AllComponents.OrderBy(c => c.ComponentStartTime);
var componentsList = new List<JsonDataMap>();
foreach (var cmp in components)
{
var componentMap = new JsonDataMap();
componentsList.Add(componentMap);
var parameterized = cmp as IExternallyParameterized;
var instrumentable = cmp as IInstrumentable;
componentMap["instrumentable"] = instrumentable != null;
componentMap["instrumentationEnabled"] = instrumentable != null ? instrumentable.InstrumentationEnabled : false;
componentMap["SID"] = cmp.ComponentSID;
componentMap["startTime"] = Azos.Apps.Terminal.Cmdlets.App.DetailedComponentDateTime( cmp.ComponentStartTime );
componentMap["tp"] = cmp.GetType().FullName;
if (cmp.ComponentCommonName.IsNotNullOrWhiteSpace()) componentMap["commonName"] = cmp.ComponentCommonName;
if (cmp is INamed) componentMap["name"] = ((INamed)cmp).Name;
if (cmp.ComponentDirector != null) componentMap["director"] = cmp.ComponentDirector.GetType().FullName;
if (parameterized == null) continue;
var pars = group.IsNotNullOrWhiteSpace() ? parameterized.ExternalParametersForGroups(group) : parameterized.ExternalParameters;
if (pars == null) continue;
pars = pars.Where(p => p.Key != "InstrumentationEnabled").OrderBy(p => p.Key);
if (pars.Count() == 0) continue;
var parameters = new List<JsonDataMap>();
foreach(var par in pars)
{
object val;
if (!parameterized.ExternalGetParameter(par.Key, out val)) continue;
var parameterMap = new JsonDataMap();
string[] plist = null;
var tp = par.Value;
if (tp == typeof(bool)) plist = new string[] { "true", "false" };
else if (tp.IsEnum) plist = Enum.GetNames(tp);
parameterMap["key"] = par.Key;
parameterMap["plist"] = plist;
parameterMap["val"] = val;
parameters.Add(parameterMap);
}
componentMap["params"] = parameters;
}
return new { OK = true, components = componentsList };
}
19
Source : RecordModelGenerator.cs
with MIT License
from azist
with MIT License
from azist
protected virtual JsonDataMap FieldDefToJSON(Doc doc,
string schema,
Schema.FieldDef fdef,
string target,
Atom isoLang,
ModelFieldValueListLookupFunc valueListLookup)
{
var result = new JsonDataMap();
result["Name"] = fdef.Name;
result["Type"] = MapCLRTypeToJS(fdef.NonNullableType);
var key = fdef.AnyTargetKey;
if (key) result["Key"] = key;
if (fdef.NonNullableType.IsEnum)
{ //Generate default lookupdict for enum
var names = Enum.GetNames(fdef.NonNullableType);
var values = new JsonDataMap(true);
foreach(var name in names)
values[name] = name;
result["LookupDict"] = values;
}
var attr = fdef[target];
if (attr!=null)
{
if (attr.Description!=null) result["Description"] = OnLocalizeString(schema, "Description", attr.Description, isoLang);
var str = attr.StoreFlag==StoreFlag.OnlyStore || attr.StoreFlag==StoreFlag.LoadAndStore;
if (!str) result["Stored"] = false;
if (attr.Required) result["Required"] = attr.Required;
if (!attr.Visible) result["Visible"] = attr.Visible;
if (attr.Min!=null) result["MinValue"] = attr.Min;
if (attr.Max!=null) result["MaxValue"] = attr.Max;
if (attr.MinLength>0) result["MinSize"] = attr.MinLength;
if (attr.MaxLength>0) result["Size"] = attr.MaxLength;
if (attr.Default!=null) result["DefaultValue"] = attr.Default;
if (attr.ValueList.IsNotNullOrWhiteSpace())
{
var vl = OnLocalizeString(schema, "LookupDict", attr.ValueList, isoLang);
result["LookupDict"] = FieldAttribute.ParseValueListString(vl);
}
else
{
var valueList = valueListLookup!=null ? valueListLookup(this, doc, fdef, target, isoLang)
: doc.GetDynamicFieldValueList(fdef, target, isoLang);
if (valueList==null && attr.HasValueList)
valueList = attr.ParseValueList();
if (valueList!=null)
result["LookupDict"] = valueList;
}
if (attr.Kind!=DataKind.Text) result["Kind"] = MapCLRKindToJS(attr.Kind);
if (attr.CharCase!=CharCase.AsIs) result["Case"] = MapCLRCharCaseToJS(attr.CharCase);
if (attr.Metadata!=null)
{
var sect = attr.Metadata[METADATA_CONFIG_FIELD];
if(sect.Exists)
result[METADATA_CONFIG_FIELD] = sect.ToConfigurationJSONDataMap();
foreach(var mAt in attr.Metadata.Attributes)
{
var fn = mAt.Name;
if (!METADATA_FIELDS.Contains(fn)) continue;
var mv = mAt.Value;
if (mv.IsNullOrWhiteSpace()) continue;
if (fn=="Description"||fn=="Placeholder"||fn=="LookupDict"||fn=="Hint")
mv = OnLocalizeString(schema, fn, mv, isoLang);
result[fn] = mv;
}
}
}
return result;
}
19
Source : PacketDocumentView.axaml.cs
with The Unlicense
from BAndysc
with The Unlicense
from BAndysc
private void TextAreaOnTextEntered(object? sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
var word = GetLastWord(editor.CaretOffset - 2).ToLower();
if (word != "packet" && word != "smsg" && word != "cmsg")
return;
_completionWindow = new CompletionWindow(editor.TextArea);
_completionWindow.Closed += CompletionWindowOnClosed;
var data = _completionWindow.CompletionList.CompletionData;
if (word == "packet")
{
data.Add(new CompletionData("id", "(int) Number of packet"));
data.Add(new CompletionData("originalId", "(int) Original number of packet. If split UPDATE_OBJECT is disabled, then this is the same as Id. If splitting is enabled, then this field contains original packet number"));
data.Add(new CompletionData("text", "(string) Raw packet output from Packet Parser"));
data.Add(new CompletionData("opcode", "(string) String representation of packet opcode (e.g. SMSG_CHAT)"));
data.Add(new CompletionData("entry", "(int) Entry of main object in packet. E.g. caster for SMSG_SPELL_GO. 0 for packets without 'main object' (e.g. SMSG_UPDATE_OBJECT)"));
}
else if (word == "smsg")
{
foreach (var smsg in Enum.GetNames<ServerOpcodes>())
data.Add(new CompletionData(smsg, null));
}
else if (word == "cmsg")
{
foreach (var cmsg in Enum.GetNames<ClientOpcodes>())
data.Add(new CompletionData(cmsg, null));
}
_completionWindow.Show();
}
}
19
Source : MethodCall_Hash_Test.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
private Argument GetRandomArgument(Random random)
{
int range = Enum.GetNames(typeof(EventArgType)).Length;
EventArgType eType = (EventArgType) random.Next(0, range);
switch (eType)
{
case EventArgType.Null:
return Argument.Null;
case EventArgType.MBObjectManager:
return Argument.MBObjectManager;
case EventArgType.MBObject:
return new Argument(new MBGUID((uint) random.Next()));
case EventArgType.Int:
return new Argument(random.Next());
case EventArgType.Float:
return new Argument((float) random.NextDouble());
case EventArgType.StoreObjectId:
return new Argument(new ObjectId((uint) random.Next()));
case EventArgType.CurrentCampaign:
return Argument.CurrentCampaign;
case EventArgType.SmallObjectRaw:
int[] intArray = {random.Next(), random.Next()};
byte[] raw = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, raw, 0, raw.Length);
return new Argument(raw);
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : ArgumentSerializer.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
private static int GetNumberOfBitsForArgType()
{
var numberOfValues = Enum.GetNames(typeof(EventArgType)).Length;
return Convert.ToInt32(Math.Ceiling(Math.Log(numberOfValues, 2)));
}
19
Source : PEFile.cs
with MIT License
from barry-jones
with MIT License
from barry-jones
private void Initialise(PeCoffFile peCoffFile)
{
Entries.Add(new Entry("File Header"));
// Initialise the display of the PE Header entries
Entry peHeader = new Entry("PE Header");
Entries.Add(peHeader);
string[] names = Enum.GetNames(typeof(TheBoxSoftware.Reflection.Core.PE.DataDirectories));
foreach (string name in names)
{
peHeader.Children.Add(Entry.Create(name));
}
// Initialise the section entries
Entry sections = new Entry("Sections");
Entries.Add(sections);
foreach (TheBoxSoftware.Reflection.Core.PE.SectionHeader header in peCoffFile.SectionHeaders)
{
sections.Children.Add(Entry.Create(header.Name));
}
// Initialise the view of the different directories
Entry directories = new Entry("Directories");
Entries.Add(directories);
foreach (KeyValuePair<DataDirectories, Directory> directory in peCoffFile.Directories)
{
directories.Children.Add(Entry.Create(directory.Value));
}
}
19
Source : PropertyManager.cs
with MIT License
from Battlerax
with MIT License
from Battlerax
[Command("propertytypes"), Help(HelpManager.CommandGroups.AdminLevel5, "Lists all property types.", null)]
public void Propertytypes(Player player)
{
var account = player.GetAccount();
if (account.AdminLevel >= 5)
{
NAPI.Chat.SendChatMessageToPlayer(player, "______ Listing Property Types ______");
foreach (var type in Enum.GetNames(typeof(PropertyTypes)))
{
NAPI.Chat.SendChatMessageToPlayer(player, "* " + type);
}
NAPI.Chat.SendChatMessageToPlayer(player, "____________________________________");
}
}
19
Source : EnumHelper.cs
with MIT License
from bbepis
with MIT License
from bbepis
public static string GetNames( Type flagType, object value )
{
var attr = (FlagsAttribute)flagType.GetCustomAttributes( typeof( FlagsAttribute ), false ).FirstOrDefault();
if( attr == null )
{
return Enum.GetName( flagType, value );
}
else
{
var validEnumValues = Enum.GetValues( flagType );
var stringValues = Enum.GetNames( flagType );
var names = string.Empty;
foreach( var stringValue in stringValues )
{
var parsedEnumValue = Enum.Parse( flagType, stringValue, true );
foreach( var validEnumValue in validEnumValues )
{
long validIntegerValue = Convert.ToInt64( validEnumValue );
long integerValue = Convert.ToInt64( value );
if( ( integerValue & validIntegerValue ) != 0 && Equals( parsedEnumValue, validEnumValue ) )
{
names += stringValue + ";";
break;
}
}
}
if( names.EndsWith( ";" ) )
{
names = names.Substring( 0, names.Length - 1 );
}
return names;
}
}
19
Source : EnumUtility.cs
with Apache License 2.0
from bcgov
with Apache License 2.0
from bcgov
public static T ToEnum<T>(string enumStr, bool useAttribute = false)
where T : Enum
{
if (useAttribute)
{
Type enumType = typeof(T);
foreach (var name in Enum.GetNames(enumType))
{
FieldInfo? field = enumType.GetField(name);
if (field != null)
{
EnumMemberAttribute attr = ((EnumMemberAttribute[])field.GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
if (attr.Value == enumStr)
{
return (T)Enum.Parse(enumType, name);
}
}
}
}
return (T)Enum.Parse(typeof(T), enumStr);
}
19
Source : FrmProperties.cs
with Apache License 2.0
from beetlex-io
with Apache License 2.0
from beetlex-io
public override void Init()
{
this.Control.DropDownStyle = ComboBoxStyle.DropDownList;
Array names = Enum.GetNames(Property.PropertyType);
foreach (var item in names)
{
this.Control.Items.Add(item.ToString());
}
base.Init();
}
19
Source : AssemblyLoader.cs
with Apache License 2.0
from beetlex-io
with Apache License 2.0
from beetlex-io
private string CodeBuilder(Type type, string test)
{
StringBuilder sb = new StringBuilder();
PropertyInfo property = type.GetProperty("Config");
string emunname = "Test_Enumn_";
if (property != null)
{
Type ptype = property.PropertyType;
if (ptype.IsEnum)
{
Array values = Enum.GetValues(ptype);
Array names = Enum.GetNames(ptype);
sb.AppendLine("public enum Test_Enumn1");
sb.AppendLine("{");
for (int i = 0; i < names.Length; i++)
{
if (i > 0)
sb.Append(",\r\n");
sb.AppendFormat("{0}={1}", names.GetValue(i), (int)Enum.Parse(ptype, names.GetValue(i).ToString()));
}
sb.AppendLine("}");
sb.AppendLine("public clreplaced " + test + "_Config");
sb.AppendLine("{");
sb.AppendLine("[System.ComponentModel.Category(\"Case Config\")]");
sb.AppendLine(string.Format("public {0} Value {{get;set;}}", "Test_Enumn1"));
sb.AppendLine("}");
}
else if (ptype.IsValueType || ptype == typeof(string))
{
sb.AppendLine("public clreplaced " + test + "_Config");
sb.AppendLine("{");
sb.AppendLine("[System.ComponentModel.Category(\"Case Config\")]");
sb.AppendLine(string.Format("public {0} Value {{get;set;}}", ptype.FullName));
sb.AppendLine("}");
}
else
{
sb.AppendLine("public clreplaced " + test + "_Config");
sb.AppendLine("{");
foreach (PropertyInfo pp in ptype.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pp.PropertyType.IsEnum)
{
Array values = Enum.GetValues(pp.PropertyType);
Array names = Enum.GetNames(pp.PropertyType);
emunname = emunname + "a";
sb.AppendLine("public enum " + emunname);
sb.AppendLine("{");
for (int i = 0; i < names.Length; i++)
{
if (i > 0)
sb.Append(",\r\n");
sb.AppendFormat("{0}={1}", names.GetValue(i), (int)Enum.Parse(pp.PropertyType, names.GetValue(i).ToString()));
}
sb.AppendLine("}");
}
PropertyLabelAttribute pla = pp.GetCustomAttribute<PropertyLabelAttribute>();
if (pla != null)
sb.AppendLine(string.Format("[Beetle.DTCore.PropertyLabel(\"{0}\",\"{1}\")]", pla.Name, pla.Remark));
PropertyAttribute pas = pp.GetCustomAttribute<PropertyAttribute>();
if (pas != null && pas.Type == PropertyType.Remark)
sb.AppendLine("[Beetle.DTCore.Property(Type = Beetle.DTCore.PropertyType.Remark)]");
sb.AppendLine("[System.ComponentModel.Category(\"Case Config\")]");
if (pp.PropertyType.IsEnum)
{
sb.AppendLine(string.Format("public {0} {1} {{get;set;}}", emunname, pp.Name));
}
else if (pp.PropertyType.IsValueType || pp.PropertyType == typeof(string))
{
sb.AppendLine(string.Format("public {0} {1} {{get;set;}}", pp.PropertyType.FullName, pp.Name));
}
}
sb.AppendLine("}");
}
}
return sb.ToString();
}
19
Source : ConfigEntryBase.cs
with GNU Lesser General Public License v2.1
from BepInEx
with GNU Lesser General Public License v2.1
from BepInEx
public void WriteDescription(StreamWriter writer)
{
if (!string.IsNullOrEmpty(Description.Description))
writer.WriteLine($"## {Description.Description.Replace("\n", "\n## ")}");
writer.WriteLine("# Setting type: " + SettingType.Name);
writer.WriteLine("# Default value: " + TomlTypeConverter.ConvertToString(DefaultValue, SettingType));
if (Description.AcceptableValues != null)
{
writer.WriteLine(Description.AcceptableValues.ToDescriptionString());
}
else if (SettingType.IsEnum)
{
writer.WriteLine("# Acceptable values: " + string.Join(", ", Enum.GetNames(SettingType)));
if (SettingType.GetCustomAttributes(typeof(FlagsAttribute), true).Any())
writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)");
}
}
19
Source : UI_MapBulkSpawn.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
void Start()
{
BulkSpawnPresetMode.ClearOptions();
string[] smChoices = Enum.GetNames(typeof(BulkSpawnPreset));
foreach (string sm in smChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = UI_MapItemTile.AddNewlinesAfterCapitals(sm, ' ');
BulkSpawnPresetMode.options.Add(newVal);
}
BulkSpawnPresetMode.onValueChanged.AddListener(delegate { CurrentSpawnPreset = (BulkSpawnPreset)BulkSpawnPresetMode.value; updateItemCount(); });
BulkSpawnPresetMode.value = 0;
BulkSpawnPresetMode.RefreshShownValue();
SpawnDir.ClearOptions();
smChoices = new string[4] { "South-east ↘", "South-west ↙", "North-west ↖", "North-east ↗" };
foreach (string sm in smChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = sm;
SpawnDir.options.Add(newVal);
}
SpawnDir.onValueChanged.AddListener(delegate { CurrentSpawnDirection = (SpawnDirection)SpawnDir.value; });
SpawnDir.value = 0;
SpawnDir.RefreshShownValue();
ItemMultiplier.onValueChanged.AddListener(delegate { updateItemCount(); });
updateItemCount();
}
19
Source : UI_WrappingControl.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
private void Start()
{
//IL_004b: Unknown result type (might be due to invalid IL or missing references)
//IL_0051: Expected O, but got Unknown
//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
//IL_00d1: Expected O, but got Unknown
WrapToggle.onValueChanged.AddListener(delegate
{
setWrapped(WrapToggle.isOn);
});
wrapTypeNames = Enum.GetNames(typeof(ItemWrapping));
WrapType.ClearOptions();
string[] array = wrapTypeNames;
foreach (string text in array)
{
Dropdown.OptionData val = new Dropdown.OptionData();
val.text=(text);
WrapType.options.Add(val);
}
WrapType.onValueChanged.AddListener(delegate
{
ChangeItemWrap(WrapType.value);
});
WrapType.RefreshShownValue();
wrapColorNames = Enum.GetNames(typeof(ItemWrappingPaper));
WrapColor.ClearOptions();
array = wrapColorNames;
foreach (string text2 in array)
{
Dropdown.OptionData val2 = new Dropdown.OptionData();
val2.text=(text2);
WrapColor.options.Add(val2);
}
WrapColor.onValueChanged.AddListener(delegate
{
ChangeItemColor(WrapColor.value);
});
WrapColor.RefreshShownValue();
setWrapped(WrapToggle.isOn);
}
19
Source : ComboItem.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
public static List<ComboItem> GetArray<T>(Type t) where T : struct, IFormattable
{
var names = Enum.GetNames(t);
var values = (T[])Enum.GetValues(t);
var acres = new List<ComboItem>(names.Length);
for (int i = 0; i < names.Length; i++)
acres.Add(new ComboItem($"{names[i]} - {values[i]:X}", (ushort)(object)values[i]));
acres.SortByText();
return acres;
}
19
Source : UI_TurnipStonk.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
void Start()
{
currentStonk = new TurnipStonk();
PatternDropdown.ClearOptions();
string[] patChoices = Enum.GetNames(typeof(TurnipPattern));
foreach (string pt in patChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = pt;
PatternDropdown.options.Add(newVal);
}
PatternDropdown.RefreshShownValue();
PatternDropdown.onValueChanged.AddListener(delegate { currentStonk.Pattern = (TurnipPattern)PatternDropdown.value; });
FeverStart.onValueChanged.AddListener(delegate { currentStonk.FeverStart = uint.Parse(FeverStart.text); });
BuyPrice.onValueChanged.AddListener(delegate { currentStonk.BuyPrice = uint.Parse(BuyPrice.text); });
MonAM.onValueChanged.AddListener(delegate { currentStonk.SellMondayAM = uint.Parse(MonAM.text); });
MonPM.onValueChanged.AddListener(delegate { currentStonk.SellMondayPM = uint.Parse(MonPM.text); });
TueAM.onValueChanged.AddListener(delegate { currentStonk.SellTuesdayAM = uint.Parse(TueAM.text); });
TuePM.onValueChanged.AddListener(delegate { currentStonk.SellTuesdayPM = uint.Parse(TuePM.text); });
WedAM.onValueChanged.AddListener(delegate { currentStonk.SellWednesdayAM = uint.Parse(WedAM.text); });
WedPM.onValueChanged.AddListener(delegate { currentStonk.SellWednesdayPM = uint.Parse(WedPM.text); });
ThuAM.onValueChanged.AddListener(delegate { currentStonk.SellThursdayAM = uint.Parse(ThuAM.text); });
ThuPM.onValueChanged.AddListener(delegate { currentStonk.SellThursdayPM = uint.Parse(ThuPM.text); });
FriAM.onValueChanged.AddListener(delegate { currentStonk.SellFridayAM = uint.Parse(FriAM.text); });
FriPM.onValueChanged.AddListener(delegate { currentStonk.SellFridayPM = uint.Parse(FriPM.text); });
SatAM.onValueChanged.AddListener(delegate { currentStonk.SellSaturdayAM = uint.Parse(SatAM.text); });
SatPM.onValueChanged.AddListener(delegate { currentStonk.SellSaturdayPM = uint.Parse(SatPM.text); });
SunAM.onValueChanged.AddListener(delegate { currentStonk.SellSundayAM = uint.Parse(SunAM.text); });
SunPM.onValueChanged.AddListener(delegate { currentStonk.SellSundayPM = uint.Parse(SunPM.text); });
RAMOffset.text = TurnipValuesAddress;
RAMOffset.onValueChanged.AddListener(delegate { TurnipValuesAddress = RAMOffset.text; });
}
19
Source : UI_MapFindAndReplace.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
void Start()
{
MatchMode.ClearOptions();
string[] smChoices = Enum.GetNames(typeof(FindAndReplaceOptions));
foreach (string sm in smChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = UI_MapItemTile.AddNewlinesAfterCapitals(sm, ' ');
MatchMode.options.Add(newVal);
}
MatchMode.onValueChanged.AddListener(delegate { CurrentOption = (FindAndReplaceOptions)MatchMode.value; });
MatchMode.value = 0;
MatchMode.RefreshShownValue();
SearchWindow.OnNewItemSelected += updateItem;
SearchWindow.OnReturnSearchWindow += updateItemVals;
ResetAll();
}
19
Source : UI_MapTerrain.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
void Start()
{
SelectMode.ClearOptions();
string[] smChoices = Enum.GetNames(typeof(TerrainSelectMode));
foreach (string sm in smChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = sm;
SelectMode.options.Add(newVal);
}
SelectMode.onValueChanged.AddListener(delegate { CurrentSelectMode = (TerrainSelectMode)SelectMode.value; });
SelectMode.value = 0;
SelectMode.RefreshShownValue();
AffectingMode.ClearOptions();
string[] amChoices = Enum.GetNames(typeof(AffectMode));
foreach (string am in amChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = am;
AffectingMode.options.Add(newVal);
}
AffectingMode.onValueChanged.AddListener(delegate { CurrentAffectMode = (AffectMode)AffectingMode.value; UpdateLayerImage(); });
AffectingMode.value = 0;
AffectingMode.RefreshShownValue();
AcreTileMap.PopulateGrid();
itemTiles = new List<UI_MapItemTile>();
foreach (var cell in AcreTileMap.SpawnedCells)
itemTiles.Add(cell.GetComponent<UI_MapItemTile>());
GridSelector.OnSelectorChanged += updateAcreGrid;
UnfetchedBlocker.gameObject.SetActive(true);
SearchWindow.OnNewItemSelected += updateItem;
LoadLastButton.gameObject.SetActive(checkAndLoadForExistingFiles());
updatePositionText();
}
19
Source : UI_Map.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
void Start()
{
RAMOffset.text = MapAddress;
RAMOffset.onValueChanged.AddListener(delegate { MapAddress = RAMOffset.text; });
ButtonLabel.text = $"Remove every {currentRemovalItem.ToString().ToLower()}";
RemoveItemMode.ClearOptions();
string[] riChoices = Enum.GetNames(typeof(RemovalItem));
foreach (string ri in riChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = ri;
RemoveItemMode.options.Add(newVal);
}
RemoveItemMode.onValueChanged.AddListener(delegate { currentRemovalItem = (RemovalItem)RemoveItemMode.value; ButtonLabel.text = $"Remove every {currentRemovalItem.ToString().ToLower()}"; });
RemoveItemMode.value = 0;
RemoveItemMode.RefreshShownValue();
}
19
Source : UI_Settings.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
void Start()
{
SearchMode.ClearOptions();
string[] smChoices = Enum.GetNames(typeof(StringSearchMode));
foreach(string sm in smChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = sm;
SearchMode.options.Add(newVal);
}
SearchMode.value = (int)GetSearchMode();
SearchMode.RefreshShownValue();
LanguageField.ClearOptions();
string[] langChoices = GameLanguage.AvailableLanguageCodes;
foreach(string lm in langChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = lm;
LanguageField.options.Add(newVal);
}
LanguageField.value = GetLanguage();
LanguageField.RefreshShownValue();
Offset.text = SysBotController.CurrentOffset;
ThreadSleepTime.text = GetThreadSleepTime().ToString();
PrefixSBAC.text = GetPrefix().ToString();
ValidataData.isOn = GetValidateData();
CatalogueToggle.isOn = GetCatalogueMode();
#if PLATFORM_ANDROID || UNITY_STANDALONE || UNITY_EDITOR
InjectionMode.ClearOptions();
string[] injChoices = Enum.GetNames(typeof(InjectionProtocol));
foreach (string insj in injChoices)
{
Dropdown.OptionData newVal = new Dropdown.OptionData();
newVal.text = insj;
InjectionMode.options.Add(newVal);
}
InjectionMode.value = (int)GetInjectionProtocol();
InjectionMode.RefreshShownValue();
InjectionMode.onValueChanged.AddListener(delegate {
SetInjectionProtocol((InjectionProtocol)InjectionMode.value);
if (UI_Sysbot.LastLoadedUI_Sysbot != null)
UI_Sysbot.LastLoadedUI_Sysbot.SetInjectionProtocol((InjectionProtocol)InjectionMode.value);
});
#else
InjectionMode.gameObject.SetActive(false);
#endif
SearchMode.onValueChanged.AddListener(delegate { setSearchMode((StringSearchMode)SearchMode.value); });
LanguageField.onValueChanged.AddListener(delegate { SetLanguage(LanguageField.value); });
Offset.onValueChanged.AddListener(delegate { SysBotController.CurrentOffset = Offset.text; });
ThreadSleepTime.onValueChanged.AddListener(delegate { SetThreadSleepTime(int.Parse(ThreadSleepTime.text)); });
PrefixSBAC.onValueChanged.AddListener(delegate { SetPrefix(PrefixSBAC.text); });
ValidataData.onValueChanged.AddListener(delegate { SetValidateData(ValidataData.isOn); });
CatalogueToggle.onValueChanged.AddListener(delegate { SetCatalogueMode(CatalogueToggle.isOn); });
// player index
string[] choices = new string[8];
for (int i = 0; i < 8; ++i)
choices[i] = string.Format("Player {0}", (char)((uint)'A' + i)); // 'A' + i
generatePlayerIndexList(choices, GetPlayerIndex());
SetLanguage(GetLanguage());
}
19
Source : Kit.Enum.cs
with MIT License
from BigBigZBBing
with MIT License
from BigBigZBBing
public static IDictionary<int, string> ToEnumKeyValue(Type type)
{
if (!type.IsEnum) throw new TypeAccessException();
string[] Names = Enum.GetNames(type);
Array Values = Enum.GetValues(type);
IDictionary<int, string> dic = new Dictionary<int, string>();
for (int i = 0; i < Values.Length; i++)
{
dic.Add((int)Values.GetValue(i), Names[i].ToString());
}
return dic;
}
19
Source : Kit.Enum.cs
with MIT License
from BigBigZBBing
with MIT License
from BigBigZBBing
public static IDictionary<int, string> ToEnumKeyDisplay(Type type)
{
if (!type.IsEnum) throw new TypeAccessException();
string[] Names = Enum.GetNames(type);
Array Values = Enum.GetValues(type);
IDictionary<int, string> dic = new Dictionary<int, string>();
string desc = string.Empty;
for (int i = 0; i < Values.Length; i++)
{
object t = Enum.Parse(type, Values.GetValue(i).ToString());
MemberInfo[] memInfo = type.GetMember(t.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
if (attrs != null && attrs.Length > 0)
{
desc = ((DisplayAttribute)attrs[0]).Value;
}
}
dic.Add((int)Values.GetValue(i), string.IsNullOrEmpty(desc) ? Names[i].ToString() : desc);
}
return dic;
}
19
Source : ParseDirective.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
private static void CaptureTransformation(Action<string> writeLine, TokenCollection? args, string description)
{
writeLine(description);
if (args is { })
{
var maxTokenTypeNameLength = Enum.GetNames(typeof(TokenType)).Max(n => n.Length);
foreach (var arg in args)
{
var outputFormat = $" {{0, -{maxTokenTypeNameLength}}}: {{1}}";
writeLine(string.Format(outputFormat, arg.TokenType, arg.RawValue));
}
}
}
19
Source : EnumTypeDescriptor.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
public IEnumerable<string> GetAllowedValues(IArgument argument)
{
return Enum.GetNames(argument.TypeInfo.UnderlyingType);
}
19
Source : FrmMain.cs
with MIT License
from bitbrute
with MIT License
from bitbrute
private void AddHost(Host host)
{
if (GetAllHosts().Contains(host))
return;
var item = new ListViewItem(new string[Enum.GetNames(typeof(HostColumn)).Length])
{
Tag = host
};
lvwHosts.Items.Add(item);
UpdateHostListView(host);
}
19
Source : System_EnumWrap.cs
with MIT License
from bjfumac
with MIT License
from bjfumac
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetNames(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
System.Type arg0 = ToLua.CheckMonoType(L, 1);
string[] o = System.Enum.GetNames(arg0);
ToLua.Push(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
See More Examples