简体   繁体   English

类中所有值类型的常规函数

[英]General function for all value types in class

I'm trying to accomplish the following within a class: 我正在尝试在课程中完成以下内容:

public void Test(var input)
{
    WriteToFile(input.ToString());
}

private void WriteToFile(string input)
{
    .....
}

But the 'var' statement can not be used within a class. 但'var'语句不能在类中使用。 So I'm wondering what the easiest way is to accomplish the same thing as above. 所以我想知道最简单的方法是如何完成与上面相同的事情。

One solution would be to create a function for each value type, but that must be more trouble than necessary: 一种解决方案是为每种值类型创建一个函数,但这必然比必要的麻烦更多:

public void Test(string input)
{
    WriteToFile(input);
}

public void Test(int input)
{
    WriteToFile(input.ToString());
}

public void Test(double input)
{
    WriteToFile(input.ToString());
}

private void WriteToFile(string input)
{
    .....
}

EDIT : When giving it some more thought I understood that this wasn't really the answer to my problems. 编辑 :当更多地考虑它时,我明白这不是我的问题的答案。 I'm posting a new question that has more thought behind it. 我发布了一个有更多想法背后的新问题。 I'm not gonna delete this question though since someone else might find this usefull. 我不会删除这个问题,因为其他人可能会觉得这个有用。

Just pass object and call ToString() on it: 只需传递object并在其上调用ToString()

public void Test(object input)
{
    WriteToFile(input.ToString());
}
public void Test<T>(T input)
{
    WriteToFile(Convert.ToString(input));
}

You could try to use public void Test(object input) 你可以尝试使用public void Test(object input)

and maybe test (input!= null) before calling the tostring method 并且可能在调用tostring方法之前测试(输入!= null)

Make the function Test accepting an object parameter and proceed after determining the type inside it. 使函数Test接受一个对象参数,并在确定其中的类型后继续。

public void Test(object input)
{
      var res = (dynamic)null;
      if (input.GetType() == typeof(String)))
      {
            res = input.ToString();
            WriteToFile(res);
      }
}

EDIT: Why this method ? 编辑:为什么这个方法?

In future, if you need to extend support to other types as well, you could do something like below (as the question talks about float, double, long, int...) 将来,如果你需要将支持扩展到其他类型,你可以做类似下面的事情(因为问题涉及float,double,long,int ......)

public void Test(object input)
{
      var res = (dynamic)null;
      if (input.GetType() == typeof(String)))
      {
            res = input.ToString();
            WriteToFile(res);
      }
      if (input.GetType() == typeof(float)))
      {
           //do some other operations here...
      }
}

Even nicer way of implementing this would be using "is" operator. 更好的实现方法就是使用“is”运算符。

      if (input is string)
      {
            res = input.ToString();
            WriteToFile(res);
      }

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

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