Parse() private method

private Parse ( Type enumType, String value ) : Object
enumType Type
value String
return Object
コード例 #1
0
        public static List <IEnumValue> GetEnumValues(Type type)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (type.IsEnum)
            {
                List <IEnumValue> Values = new List <IEnumValue>();

                foreach (string Name in Enum.GetNames(type))
                {
                    Values.Add(
                        new EnumValue()
                    {
                        Value = Convert.ChangeType(
                            Enum.Parse(type, Name),
                            Enum.GetUnderlyingType(type)
                            ).ToString(),
                        Label = Name
                    });
                }

                return(Values);
            }
            else
            {
                return(null);
            }
        }
コード例 #2
0
    public static void Main(string[] argv)
    {
        if (false)
        {
            var desc  = dx.Socket.Ex.CreateDescTemp("くみれい");
            var bytes = dx.Socket.Ex.ToByteRevenge(desc);
            Console.WriteLine($"encoded: {bytes[0]}");
            var desc02 = dx.Socket.Ex.FromByteDataRevenge(bytes);
            Console.WriteLine($"decoded: {desc.header.dataType.ToString()}, {dx.Socket.Ex.FromDescTemp(desc)}");
            return;
        }
        // C# のコマンドライン引数は 0 はじまり
        // Mode mode = (Mode)Enum.Parse(typeof(Mode), argv[0], true);
        Side side = (Side)Enum.Parse(typeof(Side), argv[1], true);

        switch (side)
        {
        case Side.Client:
        {
            Client client = new Client();
            ExecuteClientManual(client, int.Parse(argv[2]), argv[3]);
        } break;

        case Side.Server:
        {
            Server server = new Server();
            ExecuteServerManual(server, int.Parse(argv[2]));
        } break;
        }
    }
コード例 #3
0
        ///// <summary>
        ///// 变更类型
        ///// </summary>
        ///// <param name="value">值</param>
        ///// <param name="type">类型</param>
        //public static object ChangeType(string value, Type type)
        //{
        //    object obj = null;
        //    var nullableType = Nullable.GetUnderlyingType(type);
        //    try
        //    {
        //        if (nullableType != null)
        //        {
        //            if (value == null)
        //                obj = null;
        //            else
        //                obj = OtherChangeType(value, type);
        //        }
        //        else if (typeof(Enum).IsAssignableFrom(type))
        //        {
        //            obj = Enum.Parse(type, value);
        //        }
        //        else
        //        {
        //            obj = Convert.ChangeType(value, type);
        //        }
        //        return obj;
        //    }
        //    catch
        //    {
        //        return default;
        //    }
        //}

        /// <summary>
        /// 变更类型
        /// </summary>
        /// <param name="value">值</param>
        /// <param name="type">类型</param>
        /// <param name="cell">单元格</param>
        public static object ChangeType(object value, Type type, ICell cell)
        {
            try
            {
                if (value == null && type.IsGenericType)
                {
                    return(Activator.CreateInstance(type));
                }
                if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                {
                    return(null);
                }
                if (type == value.GetType())
                {
                    return(value);
                }
                if (type.IsEnum)
                {
                    if (value is string)
                    {
                        return(Enum.Parse(type, value as string));
                    }
                    else
                    {
                        return(Enum.ToObject(type, value));
                    }
                }
                if (!type.IsInterface && type.IsGenericType)
                {
                    Type   innerType  = type.GetGenericArguments()[0];
                    object innerValue = ChangeType(value, innerType, cell);
                    return(Activator.CreateInstance(type, new object[] { innerValue }));
                }
                if (value is string && type == typeof(Guid))
                {
                    return(new Guid(value as string));
                }
                if (value is string && type == typeof(Version))
                {
                    return(new Version(value as string));
                }
                if (!(value is IConvertible))
                {
                    return(value);
                }
                return(Convert.ChangeType(value, type));
            }
            catch (Exception ex)
            {
                throw new OfficeDataConvertException($"值转换失败。输入值为: {value}, 目标类型为: {type.FullName}", ex)
                      {
                          PrimitiveType = value.GetType(),
                          TargetType    = type,
                          Value         = value,
                          RowIndex      = cell.RowIndex + 1,
                          ColumnIndex   = cell.ColumnIndex + 1,
                          Name          = cell.Name,
                      };
            }
        }
コード例 #4
0
 /// <summary>
 /// 如果存在该枚举,解析字符串到字符串枚举项,否则返回默认枚举
 /// </summary>
 /// <typeparam name="TEnum">泛型枚举</typeparam>
 /// <param name="value">需转换为枚举的字符串</param>
 /// <param name="ignorecase">是否区分大小写</param>
 /// <returns>枚举项</returns>
 /// <example>
 ///     <code>
 ///         public enum EnumTwo {  None, One,}
 ///         object[] items = new object[] { "One".ParseStringToEnum《EnumTwo》(), "Two".ParseStringToEnum《EnumTwo》() };
 ///     </code>
 /// </example>
 public static TEnum ParseStringToEnum <TEnum>(this string value, bool ignorecase = default(bool))
     where TEnum : struct
 {
     return(value.IsItemInEnum <TEnum>()()
         ? default(TEnum)
         : (TEnum)Enum.Parse(typeof(TEnum), value, ignorecase));
 }
コード例 #5
0
        public string BuildSwaggerJson(IReadOnlyCollection <OcelotRouteTemplateTuple> downstreamRoutes)
        {
            var routes      = downstreamRoutes.Select(x => x.Route.DownstreamPathTemplate.Value.ToUpper()).ToList();
            var grpcMethods = _handlers.MethodList(routes);

            var doc = new OpenApiDocument
            {
                Info       = _swaggerGenOptions.SwaggerDocs.FirstOrDefault().Value,
                Paths      = new OpenApiPaths(),
                Components = new OpenApiComponents(),
                Tags       = grpcMethods
                             .Select(t => t.Value.Service.Name)
                             .Distinct()
                             .Select(x => new OpenApiTag {
                    Name = x
                })
                             .ToList()
            };

            var commentStructures = GetXmlDocs(routes);

            foreach (var(key, descriptor) in grpcMethods)
            {
                var routeTuple    = downstreamRoutes.Single(x => x.Route.DownstreamPathTemplate.Value.ToUpper() == key);
                var operationType = Enum.Parse <OperationType>(
                    routeTuple.HttpMethods.Single(m => m.Method != OperationType.Options.ToString()).Method, true);
                var httpPath = GetHttpPath(routeTuple.Route);

                commentStructures.TryGetValue((descriptor.Service.Name, descriptor.Name), out var xmlComment);

                var operation = BuildOperation(descriptor, xmlComment, doc.Components.Schemas, httpPath, operationType);

                AppendErrorResponses(operation, doc.Components.Schemas);
                AppendAuthErrorResponses(operation, routeTuple);

                if (doc.Paths.TryGetValue(httpPath, out var path))
                {
                    path.Operations.Add(operationType, operation);
                }
                else
                {
                    doc.Paths.Add(httpPath, new OpenApiPathItem {
                        Operations = { [operationType] = operation }
                    });
                }
            }


            if (_swaggerGenOptions.SecuritySchemes.TryGetValue(SecuritySchemeType.OAuth2.GetDisplayName(),
                                                               out var scheme))
            {
                doc.Components.SecuritySchemes.Add(SecuritySchemeType.OAuth2.GetDisplayName(), scheme);
            }

            doc.Components.Schemas = doc.Components.Schemas.OrderBy(x => x.Key).ToDictionary(x => x.Key, v => v.Value);
            using var writer       = new StringWriter();
            doc.SerializeAsV3(new OpenApiJsonWriter(writer));
            return(writer.ToString());
        }
コード例 #6
0
 public static Wifistuff.WlanInterface Translate(WlanInterface wlanInterface)
 {
     Wifistuff.WlanInterface result = new Wifistuff.WlanInterface
     {
         State = (Wifistuff.WlanInterface.Types.WlanInterfaceState)Enum.Parse(typeof(WlanInterfaceState),
                                                                              wlanInterface.InterfaceState.ToString())
     };
     return(result);
 }
コード例 #7
0
 protected AnonymousUserAccessMode GetAnonymousUserAccessMode()
 {
     if (string.IsNullOrEmpty(Settings["Raven/AnonymousAccess"]) == false)
     {
         var val = Enum.Parse(typeof(AnonymousUserAccessMode), Settings["Raven/AnonymousAccess"]);
         return((AnonymousUserAccessMode)val);
     }
     return(AnonymousUserAccessMode.Admin);
 }
コード例 #8
0
        /// <summary>
        ///     Converts string to enum value.
        /// </summary>
        /// <typeparam name="T">Type of enum</typeparam>
        /// <param name="value">String value to convert</param>
        /// <param name="ignoreCase">Ignore case</param>
        /// <returns>Returns enum object</returns>
        public static T ToEnum <T>(this string value, bool ignoreCase)
            where T : struct
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            return((T)Enum.Parse(typeof(T), value, ignoreCase));
        }
コード例 #9
0
 private static OpenApiSchema CreateEnumSchema(Type collectionType)
 {
     return(new OpenApiSchema
     {
         Type = "integer",
         Enum = Enum.GetNames(collectionType)
                .Select(e => new OpenApiInteger((int)Enum.Parse(collectionType, e)))
                .ToList <IOpenApiAny>(),
     });
 }
        ConvertToAcquisitionState(
            AcquisitionStateReply.Types.AcquisitionStateEnum acquisitionStateEnum)
        {
            var acquisitionState =
                (AcquisitionState)Enum.Parse(
                    typeof(AcquisitionState),
                    acquisitionStateEnum.ToString());

            return(acquisitionState);
        }
コード例 #11
0
        public virtual E GetEnum <E>(string key) where E : struct
        {
            try
            {
                return((E)Enum.Parse(typeof(E), _data.GetString(key)));
            }
            catch (JSONException)
            {
                return(default(E));

                //TODO: FIX enumClass.EnumConstants[0];
                //return enumClass.EnumConstants[0];
            }
        }
コード例 #12
0
ファイル: Enum.cs プロジェクト: qinzhixian/Part
 /// <summary>
 /// 根据值转换为指定类型的枚举成员
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="val"></param>
 /// <returns></returns>
 public static T ToEnum <T>(this string val) where T : struct
 {
     if (string.IsNullOrEmpty(val))
     {
         return(default(T));
     }
     try
     {
         return((T)SEnum.Parse(typeof(T), val, true));
     }
     catch (System.Exception ex)
     {
         throw new Util.Exception($"转换枚举失败!错误信息:{ex.Message}", ex);
     }
 }
コード例 #13
0
        //Fbar Test Mode
        private void InitTestCase()
        {
            int    i = 0;
            string tmpStr;

            Array.Resize(ref objFBar.TestCases, _dicTestFBar.Length);
            objFBar.EqNa         = _eqNa;
            objFBar.TotalTestNo  = _dicTestFBar.Length;
            objFBar.TotalChannel = _segmentParam.Length;


            foreach (Dictionary <string, string> t in _dicTestFBar)
            {
                try
                {
                    objFBar.TestCases[i]           = CreateTestCaseObj(_myUtility.ReadTcfData(t, TcfHeader.ConstTestParam));
                    objFBar.TestCases[i].TcfHeader = _myUtility.ReadTcfData(t, TcfHeader.ConstParaHeader);
                    tmpStr = _myUtility.ReadTcfData(t, TcfHeader.ConstTestParam);
                    objFBar.TestCases[i].TestPara      = (ESparamTestCase)Enum.Parse(typeof(ESparamTestCase), tmpStr);
                    objFBar.TestCases[i].ChannelNumber = int.Parse((_myUtility.ReadTcfData(t, TcfHeader.ConstChannelNo)));
                    objFBar.TestCases[i].UsePrevious   = _myUtility.ReadTcfData(t, TcfHeader.ConstUsePrev);
                    tmpStr = _myUtility.ReadTcfData(t, TcfHeader.ConstSPara);
                    objFBar.TestCases[i].SParam     = (naEnum.ESParametersDef)Enum.Parse(typeof(naEnum.ESParametersDef), tmpStr);
                    objFBar.TestCases[i].StartFreq  = _myUtility.CStr2Val(_myUtility.ReadTcfData(t, TcfHeader.ConstStartFreq));
                    objFBar.TestCases[i].StopFreq   = _myUtility.CStr2Val(_myUtility.ReadTcfData(t, TcfHeader.ConstStopFreq));
                    objFBar.TestCases[i].TargetFreq = _myUtility.CStr2Val(_myUtility.ReadTcfData(t, TcfHeader.ConstTargetFreq));
                    tmpStr = _myUtility.ReadTcfData(t, TcfHeader.ConstSearchMethod);
                    objFBar.TestCases[i].SearchType = (ESearchType)Enum.Parse(typeof(ESearchType), tmpStr.ToUpper());
                    tmpStr = _myUtility.ReadTcfData(t, TcfHeader.ConstSearchDirection);
                    objFBar.TestCases[i].SearchDirection = (ESearchDirection)Enum.Parse(typeof(ESearchDirection), tmpStr.ToUpper());
                    objFBar.TestCases[i].SearchValue     = double.Parse(_myUtility.ReadTcfData(t, TcfHeader.ConstSearchValue));
                    objFBar.TestCases[i].Interpolate     = _myUtility.CStr2Bool(_myUtility.ReadTcfData(t, TcfHeader.ConstInterpolation));
                    objFBar.TestCases[i].Abs             = _myUtility.CStr2Bool(_myUtility.ReadTcfData(t, TcfHeader.ConstAbsValue));



                    objFBar.TestCases[i].TestNo = i;
                    objFBar.TestCases[i].Initialize();
                    objFBar.TestCases[i].BuildResults();
                    i++;
                }
                catch
                {
                    MessageBox.Show(objFBar.TestCases[i].TcfHeader + " init error");
                }
            }
        }
コード例 #14
0
    //---------------------------------------------------------------------------

    #endregion

    //---------------------------------------------------------------------------

    #region Public Member Functions

    //---------------------------------------------------------------------------

    /// <summary>
    /// Raises the enable event when OCLogger is loaded.  Initialized here.
    /// </summary>
    public void OnEnable()
    {
        LogLevel logLevel = LogLevel.NONE;

        try
        {
            logLevel = (LogLevel)
                       Enum.Parse(typeof(LogLevel), OCConfig.Instance.get("LOG_LEVEL"));
        }
        catch (ArgumentException ae)
        {
            Debug.LogError
                ("In OCLogger.OnEnable: Failed to construct [" + ae.Message + "]");
        }
        CurrentLevel = logLevel;

        IsLogEnabled = logLevel > LogLevel.NONE;
    }
コード例 #15
0
ファイル: Info.cs プロジェクト: cpasyanos/PigeonVR
    void Init()
    {
        // Load data from JSON file - not implemented yet
        string filepath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);

        if (File.Exists(filepath))
        {
            // Read the json from the file into a string
            string dataAsJson = File.ReadAllText(filepath);
            // Pass the json to JsonUtility, and tell it to create a GameData object from it
            LocationDataWrapper locationData = JsonUtility.FromJson <LocationDataWrapper>(dataAsJson);
            foreach (var loc in locationData.locations)
            {
                _senders.Add((Location)Enum.Parse(typeof(Location), loc.id), loc.letters);
            }
        }
        else
        {
            Debug.LogError("Cannot load game data!");
        }
    }
コード例 #16
0
        /// <summary>
        /// 根据枚举类型返回类型中的所有值,说明
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>枚举类型字典集</returns>
        public static Dictionary <string, string> GetDictEnumDescription(Type currentType)
        {
            var dict = new Dictionary <string, string>();

            //获取字段信息
            FieldInfo[] fields = currentType.GetFields();
            if (fields == null || fields.Length < 1)
            {
                return(dict);
            }

            for (int i = 0; i < fields.Length; i++)
            {
                FieldInfo field = fields[i];

                string currentKey   = ((int)SystemEnum.Parse(currentType, field.Name)).ToString();
                string currentValue = field.Name;

                //反射自定义属性
                object[] attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);

                foreach (Attribute item in attributes)
                {
                    //类型转换找到一个Description,用Description作为成员名称
                    var currentAttribute = item as DescriptionAttribute;

                    if (currentAttribute != null)
                    {
                        currentValue = currentAttribute.Description;
                    }
                }

                dict[currentKey] = currentValue;
            }

            return(dict);
        }
コード例 #17
0
        // GET: Item
        public ActionResult CreateItem(Item item)
        {
            string path    = "";
            string imgpath = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString() + ".jpg";

            try
            {
                if (item.itemPath != null)
                {
                    string pic = System.IO.Path.GetFileName(item.itemPath.FileName);
                    // file is uploaded

                    path = System.IO.Path.Combine(
                        Server.MapPath("~/Assets/images/Items"),
                        imgpath);
                    item.itemPath.SaveAs(path);
                }
                var tipas = (enumItemType)Enum.Parse(typeof(enumItemType), item.tipas, true);
                item.tipas = tipas
                             .GetType()
                             .GetMember(tipas.ToString())
                             .FirstOrDefault()
                             ?.GetCustomAttribute <DescriptionAttribute>()
                             ?.Description
                             ?? tipas.ToString();
            }
            catch (Exception e)
            {
                throw;
            }

            var db = new ApplicationDbItem();

            db.CreateItem(item, imgpath);
            return(View("~/Views/Home/NewItem.cshtml"));
        }
コード例 #18
0
ファイル: REnum.cs プロジェクト: whztt07/MoCross
 //============================================================
 // <T>获得枚举对象中名称对应的值。</T>
 //
 // @param type 枚举对象
 // @param value 字符串
 // @return 值
 //============================================================
 public static object ToValue(Type type, string value)
 {
     return(SysEnum.Parse(type, value, true));
 }
コード例 #19
0
 /// <summary>
 /// 根据枚举值获取枚举类型
 /// </summary>
 /// <typeparam name="T">枚举类型</typeparam>
 /// <param name="currentValue">枚举的值</param>
 /// <returns>枚举值</returns>
 public static T GetEnumByEnumKey <T>(string currentValue)
 {
     return((T)SystemEnum.Parse(typeof(T), currentValue));
 }
コード例 #20
0
        private static SchemaName GetSchema(IDictionary <string, OpenApiSchema> definitions, string swaggerDataType,
                                            Type propertyType, PropertyInfo property)
        {
            if (swaggerDataType == "object")
            {
                if (!TryGetMapFieldTypes(propertyType, out var mapTypes))
                {
                    return(new SchemaName
                    {
                        Name = ToCamelCase(property.Name),
                        Schema = new OpenApiSchema
                        {
                            Reference = BuildReference(definitions, propertyType)
                        }
                    });
                }

                return(new SchemaName
                {
                    Name = ToCamelCase(property.Name),
                    Schema = new OpenApiSchema
                    {
                        Type = swaggerDataType,
                        Properties = mapTypes
                                     .DistinctBy(t => t.Name)
                                     .ToDictionary(t => ToCamelCase(t.Name), t => new OpenApiSchema
                        {
                            Type = ToSwaggerDataType(t),
                            Reference = ToSwaggerDataType(t) == "object"
                                    ? BuildReference(definitions, t)
                                    : null
                        })
                    }
                });
            }

            OpenApiSchema items = null;

            if (swaggerDataType == "array")
            {
                var collectionType = GetCollectionType(propertyType);
                var dataType       = ToSwaggerDataType(collectionType);
                if (dataType == "object")
                {
                    items = new OpenApiSchema
                    {
                        Reference = BuildReference(definitions, collectionType)
                    };
                }
                else
                {
                    items = collectionType.GetTypeInfo().IsEnum
                        ? CreateEnumSchema(collectionType)
                        : new OpenApiSchema {
                        Type = ToSwaggerDataType(collectionType)
                    };
                }
            }

            return(new SchemaName
            {
                Name = ToCamelCase(property.Name),
                Schema = new OpenApiSchema
                {
                    Type = swaggerDataType,
                    Enum = propertyType.GetTypeInfo().IsEnum
                        ? Enum.GetNames(propertyType).Select(e => new OpenApiInteger((int)Enum.Parse(propertyType, e)))
                           .ToList <IOpenApiAny>()
                        : null,
                    Items = items,
                }
            });
        }
コード例 #21
0
        public override async Task <TradesResponse> GetTrades(TradesRequest request, ServerCallContext context)
        {
            var result = new TradesResponse();

            var token   = context.GetBearerToken();
            var wallets = await _clientAccountClient.Wallets.GetClientWalletsFilteredAsync(context.GetClientId(), WalletType.Trading);

            var walletId = wallets.FirstOrDefault()?.Id;

            var response = await _walletApiV2Client.GetTradesByWalletIdAsync(
                walletId, request.AssetPairId, request.Take, request.Skip,
                request.OptionalFromDateCase == TradesRequest.OptionalFromDateOneofCase.None?(DateTimeOffset?)null : request.From.ToDateTimeOffset(),
                request.OptionalToDateCase == TradesRequest.OptionalToDateOneofCase.None?(DateTimeOffset?)null : request.To.ToDateTimeOffset(),
                request.OptionalTradeTypeCase == TradesRequest.OptionalTradeTypeOneofCase.None?null : (TradeType?)Enum.Parse(typeof(TradeType?), request.TradeType),
                token);

            if (response != null)
            {
                result.Body = new TradesResponse.Types.Body();
                result.Body.Trades.AddRange(_mapper.Map <List <TradesResponse.Types.TradeModel> >(response));
            }

            return(result);
        }
コード例 #22
0
 /// <summary>
 /// 根据枚举的int值类型转换为枚举类型
 /// </summary>
 /// <typeparam name="T">枚举类型</typeparam>
 /// <param name="currentValue">枚举的int值</param>
 /// <returns>枚举类型</returns>
 public static T GetEnumByValue <T>(int currentValue)
 {
     return((T)SystemEnum.Parse(typeof(T), currentValue.ToString()));
 }
コード例 #23
0
        private SparamTestCase.TestCaseAbstract CreateTestCaseObj(string val)
        {
            ESparamTestCase valTestCase = (ESparamTestCase)Enum.Parse(typeof(ESparamTestCase), val);

            SparamTestCase.TestCaseAbstract obj = null;
            switch (valTestCase)
            {
            case ESparamTestCase.Trigger:
            {
                obj = new SparamTrigger();
                break;
            }

            case ESparamTestCase.Mag_At:
            {
                obj = new SparamMagAt();
                break;
            }

            case ESparamTestCase.Imag_At:
            {
                obj = new SparamImagAt();
                break;
            }

            case ESparamTestCase.Freq_At:
            {
                obj = new SparamFreqAt();
                break;
            }

            case ESparamTestCase.Impedance_At:
            {
                obj = new SparamImpedanceAt();
                break;
            }

            case ESparamTestCase.Phase_At:
            {
                obj = new SparamPhaseAt();
                break;
            }

            case ESparamTestCase.Real_At:
            {
                obj = new SparamRealAt();
                break;
            }

            case ESparamTestCase.CPL_Between:
            {
                obj = new SparamCPL_Between();
                break;
            }

            case ESparamTestCase.Impendace_Bewteen:
            {
                obj = new SparamImpedance_Between();
                break;
            }

            case ESparamTestCase.Mag_Between:
            {
                obj = new SparamMagBetween();
                break;
            }

            case ESparamTestCase.Ripple_Between:
            {
                obj = new SparamRipple_Between();
                break;
            }

            case ESparamTestCase.Channel_Averaging:
            {
                obj = new SparamChannel_Avg();
                break;
            }

            case ESparamTestCase.Bandwidth:
            {
                obj = new SparamBandwith();
                break;
            }

            case ESparamTestCase.Balance:
            {
                obj = new SparamBanlance();
                break;
            }

            case ESparamTestCase.Delta:
            {
                obj = new SparamDelta();
                break;
            }

            case ESparamTestCase.Divide:
            {
                obj = new SparamDivide();
                break;
            }

            case ESparamTestCase.Relative_Gain:
            {
                obj = new SparamRelativeGain();
                break;
            }

            case ESparamTestCase.Sum:
            {
                obj = new SparamSum();
                break;
            }
            }
            return(obj);//no obj created
        }
        private static AcquisitionStateReply.Types.AcquisitionStateEnum ConvertToAcquisitionStateEnum(
            AcquisitionState acquisitionState)
        {
            var acquisitionStateEnum = (AcquisitionStateReply.Types.AcquisitionStateEnum)Enum.Parse(
                typeof(AcquisitionStateReply.Types.AcquisitionStateEnum),
                acquisitionState.ToString());

            return(acquisitionStateEnum);
        }
コード例 #25
0
 public static T Parse <T>(string value)
     where T : IFormattable, IConvertible, IComparable
 {
     return((T)SEnum.Parse(typeof(T), value));
 }
コード例 #26
0
        //Defines methods directly related to a beatmap instance, such as reading from the .osu file.

        public void ReadFile(string path, BeatmapBase result)
        {
            var            section   = "";
            ITransformable lastEvent = null;

            using (var sr = new StreamReader(osuElements.FileReaderFunc(path))) {
                var line = sr.ReadLine();
                if (line == null)
                {
                    return;
                }
                if (line.StartsWith("osu"))
                {
                    result.FormatVersion = Convert.ToInt32(line.Split(new[] { 'v', Splitter.Space }, StringSplitOptions.RemoveEmptyEntries)[3]);
                }
                else
                {
                    return;
                }
                line = sr.ReadLine();
                var hitobjects   = new List <HitObject>();
                var timingPoints = new List <TimingPoint>();
                while (line != null)
                {
                    if (line == "" || line.StartsWith("//"))
                    {
                        line = sr.ReadLine();
                        continue;
                    }
                    if (line.StartsWith(new string(Splitter.Bracket)))
                    {
                        section = line;
                        line    = sr.ReadLine();
                        continue;
                    }
                    string[] parts;
                    switch (section)
                    {
                        #region General
                    case "[General]":
                        parts    = line.Split(Splitter.Colon, StringSplitOptions.RemoveEmptyEntries);
                        parts[1] = parts[1].Trim();
                        switch (parts[0])
                        {
                        case "AudioFilename":
                            result.AudioFilename = line.Substring(line.IndexOf(':') + 2);
                            break;

                        case "AudioLeadIn":
                            result.AudioLeadIn = Convert.ToInt32(parts[1]);
                            break;

                        case "PreviewTime":
                            result.PreviewTime = Convert.ToInt32(parts[1]);
                            break;

                        case "Countdown":
                            result.Countdown = parts[1] == "1";
                            break;

                        case "SampleSet":
                            result.SampleSet = (SampleSet)Enum.Parse(typeof(SampleSet), parts[1]);
                            break;

                        case "StackLeniency":
                            result.StackLeniency = float.Parse(parts[1], IO.CULTUREINFO);
                            break;

                        case "Mode":
                            result.Mode = (GameMode)Convert.ToInt32(parts[1]);
                            break;

                        case "LetterboxInBreaks":
                            result.LetterboxInBreaks = Convert.ToBoolean(int.Parse(parts[1]));
                            break;

                        case "WidescreenStoryboard":
                            result.WidescreenStoryboard = parts[1] == "1";
                            break;

                        case ("EditorBookmarks"):         //only in first versions
                            foreach (var bookmark in parts[1].Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                result.Bookmarks.Add(int.Parse(bookmark));
                            }
                            break;

                        case ("AudioHash"):
                            result.AudioHash = parts[1];
                            break;

                        //non defaults below
                        case "StoryFireInFront":
                            result.StoryFireInFront = parts[1] == "1";
                            break;

                        case "UseSkinSprites":
                            result.UseSkinSprites = parts[1] == "1";
                            break;

                        case "AlwaysShowPlayfield":
                            result.AlwaysShowPlayfield = parts[1] == "1";
                            break;

                        case "OverlayPosition":
                            result.OverlayPosition = (OverlayPosition)Enum.Parse(typeof(OverlayPosition), parts[1]);
                            break;

                        case "SkinPreference":
                            result.SkinPreference = parts[1];
                            break;

                        case "EpilepsyWarning":
                            result.EpilepsyWarning = parts[1] == "1";
                            break;

                        case "CountdownOffset":
                            result.CountdownOffset = Convert.ToInt32(parts[1]);
                            break;

                        case "SamplesMatchPlaybackRate":
                            result.SamplesMatchPlaybackRate = parts[1] == "1";
                            break;

                        //mania only
                        case "SpecialStyle":
                            result.SpecialStyle = parts[1] == "1";
                            break;
                        }
                        break;
                        #endregion

                        #region Editor
                    case "[Editor]":
                        parts    = line.Split(Splitter.Colon, StringSplitOptions.RemoveEmptyEntries);
                        parts[1] = parts[1].Trim();
                        switch (parts[0])
                        {
                        case ("Bookmarks"):
                            if (parts.Length > 1)
                            {
                                var bms = parts[1].Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                if (bms != null)
                                {
                                    foreach (var bookmark in bms)
                                    {
                                        result.Bookmarks.Add(int.Parse(bookmark));
                                    }
                                }
                            }
                            break;

                        case ("DistanceSpacing"):
                            result.DistanceSpacing = float.Parse(parts[1], IO.CULTUREINFO);
                            break;

                        case ("BeatDivisor"):
                            result.BeatDivisor = int.Parse(parts[1]);
                            break;

                        case ("GridSize"):
                            result.GridSize = int.Parse(parts[1]);
                            break;

                        case ("TimelineZoom"):
                            result.TimelineZoom = float.Parse(parts[1], IO.CULTUREINFO);
                            break;
                        }
                        break;
                        #endregion

                        #region Metadata
                    case "[Metadata]":
                        parts = line.Split(Splitter.Colon);
                        switch (parts[0])
                        {
                        case ("Title"):
                            result.Title = parts[1];
                            break;

                        case ("TitleUnicode"):
                            result.TitleUnicode = parts[1];
                            break;

                        case ("Artist"):
                            result.Artist = parts[1];
                            break;

                        case ("ArtistUnicode"):
                            result.ArtistUnicode = parts[1];
                            break;

                        case ("Creator"):
                            result.Creator = parts[1];
                            break;

                        case ("Version"):
                            result.Version = parts[1];
                            break;

                        case ("Source"):
                            result.Source = parts[1];
                            break;

                        case ("Tags"):
                            result.Tags = parts[1];
                            break;

                        case ("BeatmapID"):
                            result.Beatmap_Id = int.Parse(parts[1]);
                            break;

                        case ("BeatmapSetID"):
                            result.BeatmapSet_Id = int.Parse(parts[1]);
                            break;
                        }
                        break;
                        #endregion

                        #region Difficulty

                    case "[Difficulty]":
                        parts = line.Split(Splitter.Colon);
                        switch (parts[0])
                        {
                        case "HpDrainRate":
                            result.HPDrainRate = float.Parse(parts[1], IO.CULTUREINFO);
                            break;

                        case "CircleSize":
                            result.CircleSize = float.Parse(parts[1], IO.CULTUREINFO);
                            break;

                        case "OverallDifficulty":
                            result.OverallDifficulty = float.Parse(parts[1], IO.CULTUREINFO);
                            break;

                        case "ApproachRate":
                            result.ApproachRate = float.Parse(parts[1], IO.CULTUREINFO);
                            break;

                        case "SliderMultiplier":
                            result.SliderMultiplier = Convert.ToDouble(parts[1], IO.CULTUREINFO);
                            break;

                        case "SliderTickRate":
                            result.SliderTickRate = float.Parse(parts[1], IO.CULTUREINFO);
                            break;
                        }
                        break;

                        #endregion

                        #region Events

                    case "[Events]":
                        EventBase ev;

                        if (EventBase.TryParse(line, out ev))
                        {
                            var videoEvent = ev as VideoEvent;
                            if (videoEvent != null)
                            {
                                result.Video = videoEvent;
                            }
                            var backgroundEvent = ev as BackgroundEvent;
                            if (backgroundEvent != null)
                            {
                                result.Background = backgroundEvent;
                            }
                            var breakEvent = ev as BreakEvent;
                            if (breakEvent != null)
                            {
                                result.BreakPeriods.Add(breakEvent);
                            }
                            var sampleEvent = ev as SampleEvent;
                            if (sampleEvent != null)
                            {
                                result.SampleEvents.Add(sampleEvent);
                            }
                            var colorEvent = ev as BackgroundColorEvent;
                            if (colorEvent != null)
                            {
                                result.BackgroundColorTransformations.Add(colorEvent);
                            }
                            if (ev is SpriteEvent)
                            {
                                var se = ev as SpriteEvent;
                                lastEvent = se;
                                switch (se.Layer)
                                {
                                case EventLayer.Background:
                                    result.BackgroundEvents.Add(se);
                                    break;

                                case EventLayer.Fail:
                                    result.FailEvents.Add(se);
                                    break;

                                case EventLayer.Pass:
                                    result.PassEvents.Add(se);
                                    break;

                                case EventLayer.Foreground:
                                    result.ForegroundEvents.Add(se);
                                    break;
                                }
                            }
                        }
                        if (line.StartsWith(" ") || line.StartsWith("_"))
                        {
                            LoopEvent l;
                            if (LoopEvent.TryParse(line, out l))
                            {
                                lastEvent = l;
                            }

                            TransformationEvent t;
                            if (TransformationEvent.TryParse(line, out t))
                            {
                                lastEvent?.AddTransformation(t);
                                //var loopEvent = t as LoopEvent;
                                //if (loopEvent != null) lastEvent = loopEvent;
                                //var triggerEvent = t as TriggerEvent;
                                //if (triggerEvent != null) lastEvent = triggerEvent;
                            }
                        }

                        break;
                        #endregion

                    case "[TimingPoints]":
                        timingPoints.Add(TimingPoint.Parse(line));
                        break;

                    case "[Colours]":
                        parts    = line.Split(Splitter.Colon);
                        parts[0] = parts[0].TrimEnd();
                        if (parts[0].StartsWith("Combo"))
                        {
                            var combo = Convert.ToInt32(parts[0].Substring(5));
                            result.ComboColours.Insert(combo - 1, ComboColour.Parse(parts[1]));
                        }
                        else if (parts[0] == "SliderBorder")
                        {
                            result.SliderBorder = (ComboColour.Parse(parts[1]));
                        }
                        else if (parts[0] == "SliderTrackOverride")
                        {
                            result.SliderTrackOverride = (ComboColour.Parse(parts[1]));
                        }

                        break;

                        #region HitObjects
                    case "[HitObjects]":
                        parts = line.Split(Splitter.Comma, StringSplitOptions.RemoveEmptyEntries);
                        var x          = Convert.ToInt32(parts[0]);
                        var y          = Convert.ToInt32(parts[1]);
                        var time       = Convert.ToInt32(parts[2]);
                        var type       = (HitObjectType)Convert.ToInt32(parts[3]);
                        var isNewCombo = type.Compare(HitObjectType.NewCombo);
                        var hitsound   = (HitObjectSoundType)Convert.ToInt32(parts[4]);


                        if (type.Compare(HitObjectType.HitCircle))                                //Make HitCircle
                        {
                            var h = new HitCircle(x, y, time, isNewCombo, type, hitsound);
                            if (parts.Length > 5)
                            {
                                h.Additions = GetAdditions(parts[5]);
                            }
                            hitobjects.Add(h);
                        }
                        if (type.Compare(HitObjectType.Spinner))                                  //Make Spinner
                        {
                            var sp = new Spinner(x, y, time, int.Parse(parts[5]), isNewCombo, hitsound);
                            if (parts.Length > 6)
                            {
                                sp.Additions = GetAdditions(parts[6]);
                            }
                            hitobjects.Add(sp);
                        }
                        if (type.Compare(HitObjectType.HoldCircle))                                  //Make HoldCircle
                        //float endtime = parts[5]
                        {
                            var hc = new HoldCircle(x, y, time, int.Parse(parts[5]), isNewCombo, type, hitsound)
                            {
                                EndTime = int.Parse(parts[5])
                            };
                            if (parts.Length > 6)
                            {
                                hc.Additions = GetAdditions(parts[6]);
                            }
                            hitobjects.Add(hc);
                        }
                        if (type.Compare(HitObjectType.Slider))                                   //Make Slider
                        {
                            var s      = new Slider(x, y, time, isNewCombo, type, hitsound);
                            var repeat = Convert.ToInt32(parts[6]);
                            var length = Convert.ToDouble(parts[7], IO.CULTUREINFO);
                            s.SegmentCount = repeat;
                            s.Length       = length;
                            var        points = parts[5].Split(Splitter.Pipe);
                            SliderType sliderType;
                            switch (points[0])
                            {
                            case "C":
                                sliderType = SliderType.Catmull;
                                break;

                            case "B":
                                sliderType = SliderType.Bezier;
                                break;

                            case "L":
                                sliderType = SliderType.Linear;
                                break;

                            case "P":
                                sliderType = SliderType.PerfectCurve;
                                break;

                            default:
                                sliderType = SliderType.Linear;
                                break;
                            }
                            s.SliderType = sliderType;
                            var pointPositions = new Position[points.Length];
                            pointPositions[0] = s.StartPosition;
                            for (var i = 1; i < points.Length; i++)
                            {
                                var p = points[i].Split(Splitter.Colon).Select(int.Parse).ToArray();
                                pointPositions[i] = Position.FromHitobject(p[0], p[1]);
                            }
                            s.ControlPoints = pointPositions;
                            int[]   sadditions;
                            int[][] pointadditions;
                            HitObjectSoundType[] pointHitsounds;
                            if (parts.Length > 8)
                            {
                                pointHitsounds = parts[8].Split(Splitter.Pipe).Select(sel => (HitObjectSoundType)int.Parse(sel)).ToArray();

                                pointadditions = null;
                                if (parts.Length > 9)
                                {
                                    sadditions = GetAdditions(parts[10]);
                                    var pas = parts[9].Split(Splitter.Pipe);
                                    pointadditions = new int[pas.Length][];
                                    for (var i = 0; i < pas.Length; i++)
                                    {
                                        pointadditions[i] = GetAdditions(pas[i]);
                                    }
                                }
                                else
                                {
                                    sadditions = new[] { 0, 0, 0, 0 };
                                }
                            }
                            else
                            {
                                sadditions     = new[] { 0, 0, 0, 0 };
                                pointHitsounds = new HitObjectSoundType[points.Length];
                                pointadditions = new int[points.Length][];
                                for (var i = 0; i < points.Length; i++)
                                {
                                    pointadditions[i] = new[] { 0, 0 };
                                }
                            }
                            s.Additions      = sadditions;
                            s.PointHisounds  = pointHitsounds;
                            s.PointAdditions = pointadditions;
                            hitobjects.Add(s);
                        }
                        break;
                        #endregion
                    }
                    line = sr.ReadLine();
                }
                hitobjects.Sort();
                result.TimingPoints = timingPoints;
                result.HitObjects   = hitobjects;
            }
        }
コード例 #27
0
ファイル: REnum.cs プロジェクト: whztt07/MoCross
 //============================================================
 // <T>获得枚举对象中名称对应的值。</T>
 //
 // @template T 枚举对象
 // @param value 字符串
 // @return 值
 //============================================================
 public static T ToValue <T>(string value)
 {
     return((T)SysEnum.Parse(typeof(T), value, true));
 }
コード例 #28
0
        // probably a bit more to do here
        private Object ConvertFromDbType(Object i)
        {
            if (i == null)
            {
                if (prop.PropertyType == typeof(String))
                {
                    return("");
                }
                else
                {
                    return(0);
                }
            }

            Object ret = null;

            switch (i)
            {
            case String s:
                if (prop.PropertyType == typeof(String))
                {
                    ret = s;
                }
                else if (prop.PropertyType == typeof(Boolean))
                {
                    if (s.ToLower() == "true")
                    {
                        ret = true;
                    }
                    else if (s.ToLower() == "false")
                    {
                        ret = false;
                    }
                    else
                    {
                        var i2 = System.Convert.ToInt32(s);
                        if (i2 != 0)
                        {
                            ret = true;
                        }
                        else
                        {
                            ret = false;
                        }
                    }
                }
                else if (prop.PropertyType.IsEnum)
                {
                    ret = Enum.Parse(prop.PropertyType, s);
                }
                else if (prop.PropertyType == typeof(Int32))
                {
                    ret = System.Convert.ToInt32(s);
                }
                else if (prop.PropertyType == typeof(Int64))
                {
                    ret = System.Convert.ToInt64(s);
                }
                else if (prop.PropertyType == typeof(Timestamp))
                {
                    if (String.IsNullOrEmpty(s))
                    {
                        ret = new Timestamp {
                            Seconds = 0
                        }
                    }
                    ;
                    else
                    {
                        ret = new Timestamp {
                            Seconds = Int64.Parse(s)
                        }
                    };
                }
                else
                {
                    ret = i;
                }
                break;

            case Int32 q:
                if (prop.PropertyType == typeof(Int32))
                {
                    ret = q;
                }
                else if (prop.PropertyType == typeof(String))
                {
                    ret = q.ToString();
                }
                else if (prop.PropertyType == typeof(Int64))
                {
                    ret = Convert.ToInt64(q);
                }
                else if (prop.PropertyType.IsEnum)
                {
                    ret = q;
                }
                else if (prop.PropertyType == typeof(Timestamp))
                {
                    ret = Timestamp.FromDateTimeOffset(DateTimeOffset.FromUnixTimeSeconds(q));
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    ret = q > 0?true:false;
                }
                break;

            case Int64 q:
                if (prop.PropertyType == typeof(Int32))
                {
                    ret = Convert.ToInt32(q);
                }
                else if (prop.PropertyType == typeof(String))
                {
                    ret = q.ToString();
                }
                else if (prop.PropertyType == typeof(Int64))
                {
                    ret = q;
                }
                else if (prop.PropertyType.IsEnum)
                {
                    ret = Convert.ToInt32(q);
                }
                else if (prop.PropertyType == typeof(Timestamp))
                {
                    ret = Timestamp.FromDateTimeOffset(DateTimeOffset.FromUnixTimeSeconds(q));
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    ret = q > 0 ? true : false;
                }
                break;

            default:
                ret = ConvertFromDbType(i.ToString());     // probably not good .... lazy ... etc.,
                break;
            }
            return(ret);
        }