基于输入的动态返回类型 - asp.net
我想创建一个有两个参数的函数
public **XYZ** GetOputput(string strToConvert, **ABC**)
我想从这个函数得到什么,我将向这个函数发送一个字符串以及我想要转换这个字符串的数据类型[例如:Int32,Int64,日期时间等..]返回值将与我作为输入参数发送的数据类型相同。
我想在我的函数中有这样的东西:
switch(//what is the data type)
case: //if data type is date than do something and return date
case: //if data type is int than do something and return int
我不知道如何动态发送、比较和返回数据类型。 帮助我
I want to create a function which would have two parameters
public **XYZ** GetOputput(string strToConvert, **ABC**)
What I want from this function, that I will send a string to this function and the datatype in which I want to convert this string [Ex: Int32,Int64, datetime etc..] and the return will be the same as the datatype I have sent as the input parameter.
I want to have something like this in my function:
switch(//what is the data type)
case: //if data type is date than do something and return date
case: //if data type is int than do something and return int
I have no idea how to send, compare and return the datatype dynamically.
Assist me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用通用函数怎么样?
因此,要从字符串中获取 int,请尝试以下操作:
How about using a generic function.
So to get an int from a string, try this:
您可以将其用于您的函数(考虑可为空类型):
You can use this for your function (takes nullable types into consideration):
如果您使用的是 .NET Framework 4.0,请使用
dynamic
use
dynamic
, if you are using .NET framework 4.0看看 Convert.ChangeType
Take a look at Convert.ChangeType
听起来你想使用泛型:
并且在使用中:
尽管检查所有接受类型的 T 类型可能有点乏味。
编辑:所以将其与米卡的答案结合起来并执行以下操作:
Sounds like you want to use Generics:
And in use:
Although inspecting the type of T for all accepted types could be a bit tedious.
edit: So combine it with Mika's answer and do: