How to pass dynamic data types as parameters in C#?
I have a method in c# which builds xml on the fly.
However, I won't know the specific elements/attributes until run-time.
How do I declare parameters when I don't know wha开发者_开发问答t the data-types, names and values or amount will be?
You are looking for params keyword. Or are you? :)
You can use System.Object
for all parameters, since it is the base class for all other types. You can then find out the actual declared type with the GetType()
method, and treat the value appropriately.
e.g.
if (myParam.GetType() == typeof(Int32))
{
// treat value as integer ...
int val = (int)myParam;
}
or you can use the syntax
if (myParam is Int32)
{
// treat value as integer ...
int val = (int)myParam;
}
else if (myParam is String)
{
string val = myParam.ToString();
}
etc.
Another option is to use generics. This will be helpful if you need to put constraints on the types that can be passed in:
public void BuildXml<T>(T obj)
{
// do work
}
Or if you are expecting a collection of objects:
public void BuildXml<T>(IEnumerable<T> items)
{
// do work
}
Then you can use reflection to get the relevant data you need.
精彩评论