期望的类,委托,枚举,接口或结构错误C# [英] expected class, delegate, enum, interface or struct error C#

查看:389
本文介绍了期望的类,委托,枚举,接口或结构错误C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个这样的PHP代码,将它转换为C#。

have a php code like this,going to convert it in to C#.

function isValid($n){
if (preg_match("/\d+/",$n) > 0 && $n<1000) {
    return true;
}
return false;
}



这里是我的try,BUT错误显示错误是expected class,delegate,枚举,接口或结构错误C#

Here is my try,BUT error shown Error is "expected class, delegate, enum, interface or struct error C#"

public string IsValidate(string Item)
{
    string Result = Item;
   try
{
Result = System.Text.RegularExpressions.Regex.Replace(InputTxt, @"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2");
}
catch(Exception ex)
{
console.WriteLine(ex.Message)
}
return Result;
}

错误是什么,试试?
i从此处获取此代码段代码

What is the error,Is there any other way to implement this better than my try ? i got this snippet from here code

推荐答案

您没有在类/结构中定义此方法,得到这个错误。您可以在类中定义此方法。

You haven't define this method inside a class/struct that is why you are getting this error. You may define this method inside a class.

public class MyValidator
    {
        public string IsValidate(string Item)
        {
          //Your code here
        }

    }

稍后您可以使用它:

MyValidator validator = new MyValidator();
validator.IsValid("Your string");

此外,在 Console.Write 末尾缺少分号code>语句,加上控制台的c应为大写

Also you are missing semicolon at the end of the Console.Write statement, plus 'c' for Console should be in uppercase

编辑在你的php代码,它看起来像你试图看看传递的字符串是否是一个整数,它小于1000,你可以使用 int.TryParse 像下面:


Since in your php code, it looks like you are trying to see if the string passed is an integer and it is less than 1000, you may use the int.TryParse like the following:

public class MyValidator
{
    public bool IsValidate(string Item)
    {
        string Result = Item;
        int val;
        if (int.TryParse(Item, out val) && val > 0 && val < 1000)
        {
            return true;
        }
        else
        {
            return false;
        }

    }
}

主要方法你可以做:

 static void Main()
        {
            MyValidator validator = new MyValidator();
            Console.WriteLine(validator.IsValidate("asdf123")); // This will print false
            Console.WriteLine(validator.IsValidate("999")); //This will print true
            Console.WriteLine(validator.IsValidate("1001")); //This will print false
         }

这篇关于期望的类,委托,枚举,接口或结构错误C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆