I am making a class that calls a callback function and I want it to pass some data in some cases but that data may vary. In C++ I would use void* but in C# it's unsafe and it means it might get GCed. Is there any way of passing unknown type of data开发者_开发问答 in C#?
You've got two options:
Generics (which allow you to specify the type when you call the method... and the object will be properly typed within the method.)
// Definition:
public void MyMethod<T>(T myParameter)
{
/* My Code */
}
// Call:
MyMethod<int>(999);
// Call:
MyMethod<bool>(false);
Or System.Object (which means you'll have to ascertain the object's actual type inside your method and cast appropriately)
// Definition:
public void MyMethod(Object myParameter)
{
/* My Code */
}
// Call:
MyMethod(999);
// Call:
MyMethod(false);
You should use Generics for this.
http://msdn.microsoft.com/en-us/library/twcad0zb.aspx
The simplest solution would be to use the object
type because all other objects inherit from this object. Doing so you allow yourself to pass in any object type.
http://msdn.microsoft.com/en-us/library/system.object.aspx
You'd pass it around at an object. Unlike C++ you'll be able to do a type safe cast in C#, whereas you can't in C++.
I think you should use Object.
If you're working in .net 4 you can also use the dynamic
type.
精彩评论