Are there "Type-unsafe" function parameters in c# and how could we make one?
public List<string> Attributes = new List<string>();
public void Add(string key, string value)
{
if (value.ToString() != "")
{
Attributes.Add(key + "=\"" + value + "\" ");
}
}
开发者_如何学Gopublic void Add(string key, int value)
{
if (value.ToString() != "")
{
Attributes.Add(key + "=\"" + value + "\" ");
}
}
So, instead of having two Add functions, could we make just one? For example
public void Add(string key, <var> value)
{
if (value.ToString() != "")
{
Attributes.Add(key + "=\"" + value + "\" ");
}
}
Note that in this case, the integer version of your function has to be converted to a string anyway for inclusion in the list. So if your entire problem is really as stated, you only need the string version of your function and can call it like this:
int SomeValue = 42;
string SomeName= "The Answer to Life, the Universe, and Everything";
Add(SomeName, SomeValue.ToString());
But if you are asking about a more general problem, you can just use the object
type, like this:
public void Add(string key, object value)
{
if (value.ToString() is {Length: >0})
{
Attributes.Add($"{key}=\"{value}\" ");
}
}
public void Add<T>(string key, T value)
{
if (value.ToString() != "")
{
Attributes.Add(key + "=\"" + value + "\" ");
}
}
usage
Add("key", 22);
Add("key", "value");
use Object for the type.
public void Add(string key, object value)
{
if(value == null) {return;}
var sval = value.ToString();
if(sval != "")
{ Attributes.Add( key + "=\"" + sval + "\""}
}
精彩评论