检查字符串是否可以转换为给定类型

时间:2017-10-08 17:45:07

标签: c#

我必须创建一个API,如果他没有在 GET 请求中提供强制参数,我需要向用户提供正确的消息,我还需要确保用户已经在参数中提供了适当的值,值可以是整数,字符串,日期或枚举。

所以我创建了一个类 SearchParameters ,其中列出了有关请求参数的信息。

private static class SearchParameters
{
    public static List<ParamInfo> ParamList = new List<ParamInfo>
    {
        new ParamInfo {Name ="location", IsMandatory = true , ExpecteDataType = typeof(ulong) } ,
        new ParamInfo {Name ="service", IsMandatory = true  , ExpecteDataType = typeof(ServiceType)} ,
        new ParamInfo {Name ="start", IsMandatory = true  , ExpecteDataType = typeof(DateTimeOffset)} ,
        new ParamInfo {Name ="appointmentType", IsMandatory = true  , ExpecteDataType = typeof(AppointmentType)} ,
        new ParamInfo {Name ="status", IsOptional = true  , ExpecteDataType = typeof(string)} ,
        new ParamInfo {Name ="end", IsOptional = true  , ExpecteDataType = typeof(DateTimeOffset)} ,
        new ParamInfo {Name ="clinicianGender", IsOptional = true , ExpecteDataType = typeof(AdministrativeGender)}   ,
        new ParamInfo {Name ="_sort", IsForSorting = true , ExpecteDataType = typeof(string)},
        new ParamInfo {Name ="_count", IsForPaging = true , ExpecteDataType = typeof(uint)}
    };
}

其中ParamInfo是类

的实例
public class ParamInfo
{
    public string Name { get; set; }
    public bool IsMandatory { get; set; }
    public bool IsRequired { get; set; }
    public bool IsOptional { get; set; }
    public bool IsForSorting { get; set; }
    public bool IsForPaging { get; set; }
    public Type ExpecteDataType { get; set; }
}

当用户请求时,我在元组列表中有可用的参数Item1&amp; Item2是字符串,Item1是查询参数&amp;的名称。 Item2是用户提供的值。

如何确保参数(即Item2)的值具有正确的数据类型?

我试过这样的事情:

// Data tye verification
foreach (ParamInfo info in SlotSearchParameters.ParamList)
{
    Tuple<string, string> param = searchparams.Parameters.Where(x => x.Item1.ToLower() == info.Name).FirstOrDefault();
    if (param != null)
    {
        Type expectedType = info.ExpecteDataType;
        // how can we check if the value of type of x.Item1 is as expected 
        // Can't procede
    }
}

但由于x.Item1始终是所提供值的字符串表示形式,可以是Date,Int或string等,我不知道该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以在ParamInfo课程中添加验证器:

public class ParamInfo
{
    public string Name { get; set; }
    public bool IsMandatory { get; set; }
    public bool IsRequired { get; set; }
    public bool IsOptional { get; set; }
    public bool IsForSorting { get; set; }
    public bool IsForPaging { get; set; }
    public Type ExpecteDataType { get; set; }
    public Predicate<string> Validator { get; set; }
}

现在:

public static List<ParamInfo> ParamList = new List<ParamInfo>
{
    new ParamInfo { Name ="location",
                   IsMandatory = true, 
                   ExpecteDataType = typeof(ulong),
                   Validator = s => s != null && ulong.TryParse(s, out var _); }

你可以像这样使用它:

foreach (ParamInfo info in SlotSearchParameters.ParamList)
{
    Tuple<string, string> param = searchparams.Parameters.Where(x => x.Item1.ToLower() == info.Name).FirstOrDefault();

    if (param != null &&
        Validator(x.Item1) //
    {
        //whatever
    }
}

}

答案 1 :(得分:1)

出于问题中所述的目的,您应使用#include <stdio.h> char **createMapBoard(void); void printMapBoard(char **board); char **destroyMapBoard(char **board); int main(){ char **board = createMapBoard(); printMapBoard(board); destroyMapBoard(board); printMapBoard(board); return 0; } char **createMapBoard(void){ char **ptr[8][8]; int i,j; char F = 'F'; char K = 'K'; char C = 'C'; char D = 'D'; char B = 'B'; int n = 8; int m = 8; for(j=0; j<8; j++){ for(i=0;i<8;i++){ ptr[j][i] = ' '; } } ptr[0][0] = F; ptr[0][1] = F; ptr[1][1] = F; ptr[2][1] = F; ptr[2][2] = F; ptr[3][2] = F; ptr[4][2] = K; ptr[5][0] = C; ptr[5][3] = B; ptr[6][1] = C; ptr[6][2] = C; ptr[6][4] = D; ptr[7][2] = C; ptr[7][5] = D; ptr[7][6] = D; printf("========\n"); for(j=0;j<8;j++){ for(i=0;i<8;i++){ printf("%c",ptr[j][i]); } printf("\n"); } printf("========\n"); printf("\n"); return **ptr; } void printMapBoard(char **board){ int j, i; printf("========\n"); for(j=0;j<8;j++){ for(i=0;i<8;i++){ printf("%c", board[j][i]); } printf("\n"); } printf("========\n"); printf("\n"); } char **destroyMapBoard(char **board){ free(**board); free(board); return 0; } (re:https://msdn.microsoft.com/en-us/library/system.int32.parse(v=vs.110).aspx)或Parse()(re:https://msdn.microsoft.com/en-us/library/zf50za27(v=vs.110).aspx)方法,例如TryParse()

希望这会有所帮助。

答案 2 :(得分:0)

  

如何确保参数(即Item2)的值具有正确的数据类型?

  1. 您可以让用户很难实际输入错误的数据类型。例如,如果他们在表单中键入内容并且您要求输入日期 - 如果他们在该字段中输入非感性内容,请将其设置为无法提交表单。
  2. 如果他们输入非感性或
  3. 的内容,您可以抛出异常
  4. 如果输入值不是正版,则可以阻止创建ParamInfo对象。请参阅下面的一些示例。
  5. 附注:您实际将数据存储在ParamInfo类中的哪个位置?如果您实际上将变量存储为int,date或enum等,那么使用此变量就可以避免使用ExpectedDataType变量。我希望这是有道理的。换句话说,您是否要将item1.value存储为ParamInfo类中的字符串?或者您想存储的是实际数字,日期还是枚举?
  6. 用户是否可能意外输入错误的ParamInfo.Name值?
  7. 无论如何,这里有一些想法可以帮助你:

    internal class Program
    {
        private static void Main(string[] args)
        {
            List<Tuple<string, string>> userInputValues = new List<Tuple<string, string>>(); // obviously implement the correct user values here
    
            // This is the money below.
            // you'll have only valid ParamInfo objects here:
    
            List<ParamInfo> paramFactory = new ParamInfoFactory(userInputValues).ValidParameters;         
        }
    
        public class ParamInfo
        {
            public string Name { get; set; }
            public bool IsMandatory { get; set; }
            public bool IsRequired { get; set; }
            public bool IsOptional { get; set; }
            public bool IsForSorting { get; set; }
            public bool IsForPaging { get; set; }
    
            public Type ExpecteDataType { get; set; } // <--- you really don't need this.
    
            // where are you storing the item1.value?
            // are you storing it as a string, or as the proper type that it represents?
        }
        public class ParamInfoFactory
        {
            public List<ParamInfo> ValidParameters { get; set; }
    
            public ParamInfoFactory(List<Tuple<string, string>> userSuppliedValues)
            {
                ValidParameters = new List<ParamInfo>();
                foreach (Tuple<string, string> userValue in userSuppliedValues)
                {
                    if (UserInputValuesAreValid(userValue))
                    {
                        // all the values are valid. you can now create and add the parameters to your list.
                        // remember to instantiate it as you wish with the right values etc in there.
                        ValidParameters.Add(new ParamInfo());
                    }
                }
            }
            private bool UserInputValuesAreValid(Tuple<string, string> userValue)
            {
                return IsNameValid(userValue.Item1) && IsDataValid(userValue.Item2);
            }
    
            private bool IsDataValid(string data)
            {
                return IsValidDate(data) || IsValidNumber(data); // you can also implement the IsValidEnum or any other method you want
            }
    
            private static bool IsValidDate(string data)
            {
                DateTime dateValue;
                bool isDate = DateTime.TryParse(data, out dateValue);
                return isDate;
            }
    
            //private static bool IsEnum(string data)
            //{
            //    Colors colorValue;
            //    bool isEnum = Enum.TryParse(data, out colorValue);
            //    return isEnum;
            //}
    
            private static bool IsValidNumber(string data)
            {
                int number;
    
                bool isNumber = Int32.TryParse(data, out number);
                return isNumber;
            }
    
            private bool IsNameValid(string userInputName)
            {
                return SearchParameters.ParamList.Any(paramInfo => paramInfo.Name == userInputName.ToLower());
            }
    
            private static class SearchParameters
            {
                public static List<ParamInfo> ParamList = new List<ParamInfo>
                {
                    new ParamInfo {Name ="location", IsMandatory = true , ExpecteDataType = typeof(ulong) } ,
                    new ParamInfo {Name ="service", IsMandatory = true  , ExpecteDataType = typeof(ServiceType)} ,
                    new ParamInfo {Name ="start", IsMandatory = true  , ExpecteDataType = typeof(DateTimeOffset)} ,
                    new ParamInfo {Name ="appointmentType", IsMandatory = true  , ExpecteDataType = typeof(AppointmentType)} ,
                    new ParamInfo {Name ="status", IsOptional = true  , ExpecteDataType = typeof(string)} ,
                    new ParamInfo {Name ="end", IsOptional = true  , ExpecteDataType = typeof(DateTimeOffset)} ,
                    new ParamInfo {Name ="clinicianGender", IsOptional = true , ExpecteDataType = typeof(AdministrativeGender)}   ,
                    new ParamInfo {Name ="_sort", IsForSorting = true , ExpecteDataType = typeof(string)},
                    new ParamInfo {Name ="_count", IsForPaging = true , ExpecteDataType = typeof(uint)}
                };
            }
        }
    }