是否可以转换类型的变量:dictionary< int,models.user>到词典< int,object>在C#? [英] Is it possible to cast a variable of type: dictionary<int, models.user> to dictionary<int, object> in C#?
问题描述
大家好。我正在开发一个c#应用程序,其中我有大约15种方法来更新数据库中的条目。所以我想用两个参数创建一个更新方法:Dictionary< int,object>字典和字符串tableName。字典的对象部分将接受不同的ViewModel。这是我的代码:
Hi, everyone. I am working on a c# application where I have about 15 methods that Update entries in the database. So I want to make one method for update with two parameters: Dictionary<int, object> dictionary and string tableName. The 'object' part of the dictionary will accept different ViewModels. Here is my code:
public void UpdateEntriesFromAGivenTable(Dictionary<int, object> dictionary, string tableName)
{
foreach (KeyValuePair<int, object> entry in dictionary)
{
Dictionary<string, object> dict = GetTypeNamesAndValuesWithReflection(entry.Value);
foreach (var item in dict)
{
if (item.Value != null && (!string.Equals(item.Key, "id")))
{
UpdateEntry(tableName, item.Key, item.Value, entry.Key);
}
}
}
}
但是当我试图使用上面的方法,我收到参数Dictionary< int,user>下面的红色下划线并且错误消息是:无法从'System.Collections.Generic.Dictionary< int,Models.User>转换到'System.Collections.Generic.Dictionary< int,object> ;.
我尝试过:
我尝试过以下演员:
(字典< int,object>)(用户)
但没有成功。我在谷歌和stackoverflow寻求帮助,但没有找到类似的问题。所以你能告诉我是否可以转换Type:Dictionary< int,Models.User>的变量。到词典< int,object>如果答案是肯定的,怎么做?谢谢。
But when I tried to use the above method, I receive the red underline below the parameter "Dictionary<int, user>" and the error message is: cannot convert from 'System.Collections.Generic.Dictionary<int, Models.User> to 'System.Collections.Generic.Dictionary<int, object>.
What I have tried:
I tried the following cast:
(Dictionary<int, object>)(users)
but without success. I looked for help in google and stackoverflow but did not find a similar issue. So can you tell me is it possible to cast a variable of Type: Dictionary<int, Models.User> to Dictionary<int, object> and if the answer is yes, how to do it? Thanks.
推荐答案
使用泛型
Use generics
public void UpdateEntriesFromAGivenTable<T>(Dictionary<int, T> dictionary, string tableName)
{
foreach (KeyValuePair<int, T> entry in dictionary)
{
Dictionary<string, object> dict = GetTypeNamesAndValuesWithReflection(entry.Value);
foreach (var item in dict)
{
if (item.Value != null && (!string.Equals(item.Key, "id")))
{
UpdateEntry(tableName, item.Key, item.Value, entry.Key);
}
}
}
}
你可以打电话它喜欢
You can call it like
Dictionary<int, User> d = new Dictionary<int, User>();
d.Add(1, new User { Name = "A" });
d.Add(2, new User { Name = "B" });
UpdateEntriesFromAGivenTable(d, "");
见这里: C#cast Dictionary< string,AnyType>到词典< string,对象> (涉及反思) - 堆栈溢出 [ ^ ]
这篇关于是否可以转换类型的变量:dictionary< int,models.user>到词典< int,object>在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!