简体   繁体   English

仅在C#中传递字符串和整数?

[英]Pass in only strings and ints in C#?

I have a function like the below. 我有一个像下面的功能。 I ran into a problem were i accidentally passes in enums when i wanted the value. 我遇到一个问题,当我想要该值时,我不小心通过了枚举。 Same problem would occur if i passed in structs or classes. 如果我在结构或类中传递同样的问题。

Is there a way i can pass call the func and only have strings and ints as my arguments? 有没有一种方法可以传递给函数,并且仅将字符串和整数作为参数?

static public string Func(string fmt, params object[] args)

You can create a paramarray of a specific type. 您可以创建特定类型的参数数组。
If you want to accept two different types, you can create a class with implicit conversions from int and string and accept a paramarray of that class. 如果要接受两种不同的类型,则可以使用intstring进行隐式转换来创建一个类,并接受该类的paramarray。

It seems that the first parameter is used to communicate the format of the data in the second parameter, the array. 似乎第一个参数用于传达第二个参数数组中的数据格式。

I would create two public methods to solve this by making use of method overloading. 我将通过使用方法重载来创建两个公共方法来解决此问题。 see http://csharp.net-tutorials.com/classes/method-overloading . 参见http://csharp.net-tutorials.com/classes/method-overloading I believe this will work for array parameters. 我相信这将适用于数组参数。

static public Func(string[] args) ... and static public Func(int[] args) ... 静态公共Func(string [] args)...和静态公共Func(int [] args)...

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

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