If I have a function that takes a reference to an object. How do I cast the parameter to avoid a type mismatch?
Dictionary<string, string> mySettings = new Dictionary<string, string>();
.
.
saveSettings(ref mySettings);
.
.
void saveSettings(ref object)
{
}
The call to saveSettings results in the following error message:
cannot convert from 'ref Dictionary' to 'ref object'
I'm not looking for a workaround, I've done that, I would like to know if this direct approach is possible.
If save settings is taking multiple types, why not use a generic instead? Esp if they share a common interface.
void saveSettings<T>(T obj);
var objectMySettings = mySettings as object;
if (objectMySettings != null)
saveSettings(ref objectMySettings);
void saveSettings(ref object)
The definition of saveSettings is malformed. You need an identifier after "ref object". But I'd make the "ref object" a Dictionary instead.
Do it this way:
protected void Button1_Click(object sender, EventArgs e)
{
Dictionary<string, string> mySettings = new Dictionary<string, string>();
saveSettings(mySettings);
}
void saveSettings( Dictionary<string, string> Settings)
{
}
Something like this:
static void Main()
{
Dictionary<string, string> mySettings = new Dictionary<string, string>();
object o = mySettings;
SaveSettings(ref o);
// o now has an item.
}
static void SaveSettings(ref object o)
{
var d = o as Dictionary<string, string>;
d.Add("Some", "String");
}
EDIT Some debugging output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.