简体   繁体   English

C#变量问题

[英]C# variable questions

I am working on a project, in C#, that needs to run a method based off of user input.我正在使用 C# 开发一个项目,该项目需要运行基于用户输入的方法。 The user can enter either a integer or a string into a text box.用户可以在文本框中输入整数或字符串。 Is it possible to create an undeclared variable and if not, how do I go about using the right method for the user input?是否有可能创建一个未声明的变量,如果没有,我该如何为用户输入使用正确的方法? I plan on creating two overloaded methods.我计划创建两个重载方法。

You can use object as type for your param and then use .GetType() or is to perform type checking.您可以使用object作为参数的类型,然后使用.GetType()is执行类型检查。 There are other alternatives like dynamic but it's more common to use dynamic when you need to perform method calls on your object without having to cast it to its actual type还有其他替代方法,例如dynamic但是当您需要对对象执行方法调用而不必将其强制转换为实际类型时,使用dynamic更为常见

Anyway if you're reading from console, it will always be a string, so you can int.TryParse() on it.无论如何,如果您从控制台读取,它将始终是一个字符串,因此您可以int.TryParse()

public void DoStuff(string param) 
{
    int chosen;
    if(int.TryParse(param, out chosen) 
    {
        // is an int do stuff with chosen
    } 
    else 
    { 
        // it's not do stuff with param
    }
}

The user can enter either a integer or a string into a text box.用户可以在文本框中输入整数或字符串。

Seems simple to me then.对我来说似乎很简单。 You get the input from the textbox through the Text property which is always a string.您可以通过 Text 属性从文本框中获取输入,该属性始终是一个字符串。 So you need to check if the input can be parsed to an integer using TryParse.因此,您需要检查输入是否可以使用 TryParse 解析为整数。 Personally I don't see why you need overloaded methods.我个人不明白为什么需要重载方法。 Are the methods the same except for the type of the param?除了参数的类型外,方法是否相同? If not I would not choose to overload but just different ones with clear naming.如果不是,我不会选择重载,而是选择具有明确命名的不同的重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM