1 // Licensed to the .NET Foundation under one or more agreements. 2 // The .NET Foundation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System; 6 using System.ComponentModel; 7 using System.Globalization; 8 9 namespace Microsoft.CSharp 10 { 11 internal abstract class CSharpModifierAttributeConverter : TypeConverter 12 { 13 protected abstract object[] Values { get; } 14 protected abstract string[] Names { get; } 15 protected abstract object DefaultValue { get; } 16 CanConvertFrom(ITypeDescriptorContext context, Type sourceType)17 public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => 18 sourceType == typeof(string) ? true : base.CanConvertFrom(context, sourceType); 19 ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)20 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) 21 { 22 string name = value as string; 23 if (name != null) 24 { 25 string[] names = Names; 26 for (int i = 0; i < names.Length; i++) 27 { 28 if (names[i].Equals(name)) 29 { 30 return Values[i]; 31 } 32 } 33 } 34 35 return DefaultValue; 36 } 37 ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)38 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 39 { 40 if (destinationType == null) 41 { 42 throw new ArgumentNullException(nameof(destinationType)); 43 } 44 45 if (destinationType == typeof(string)) 46 { 47 object[] modifiers = Values; 48 for (int i = 0; i < modifiers.Length; i++) 49 { 50 if (modifiers[i].Equals(value)) 51 { 52 return Names[i]; 53 } 54 } 55 56 return SR.toStringUnknown; 57 } 58 59 return base.ConvertTo(context, culture, value, destinationType); 60 } 61 62 public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true; 63 64 public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; 65 66 public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection(Values); 67 } 68 } 69