本文介绍了如何在C#中将对象分配给hastable值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,

这是我的代码

课程计划
{

公共静态IADXVoice ADXVoice1 =新的Envox.ADXVoice.ADXVoice();
静态void Main(string [] args)
{
哈希表objhashmap = new Hashtable();
objhashmap.Add(8533,ADXVoice1);
ICollection keytest = objhashmap.Values;
ICollection keytest1 = objhashmap.Keys;

foreach(objhashmap.Keys中的int键)
{
Console.WriteLine("{0},{1}",key,objhashmap [key]);
//Console.WriteLine("{0},{1},key,objhashmap [key]);
ADXVoice obj = objhashmap [key];//正在获取转换类型错误,因为无法将类型"object"隐式转换为"Envox.ADXVoice.ADXVoice".存在显式转换(您是否缺少演员表?)

Console.ReadKey();
}
}
}

在上面的代码中,无法将哈希表值分配给为代码中使用的dll创建的新对象.

我的要求是将对象放在哈希表中,并在需要的时候在其他地方分配上面代码中所示的示例.

谢谢,
S.Chand Basha

Hi Friends,

Here is my code

class Program
{

public static IADXVoice ADXVoice1 = new Envox.ADXVoice.ADXVoice();
static void Main(string[] args)
{
Hashtable objhashmap = new Hashtable();
objhashmap.Add(8533, ADXVoice1);
ICollection keytest = objhashmap.Values;
ICollection keytest1 = objhashmap.Keys;

foreach (int key in objhashmap.Keys)
{
Console.WriteLine("{0}, {1}", key, objhashmap[key]);
//Console.WriteLine("{0}, {1}", key, objhashmap[key]);
ADXVoice obj=objhashmap[key];// Am getting convert type error as Cannot implicitly convert type ''object'' to ''Envox.ADXVoice.ADXVoice''. An explicit conversion exists (are you missing a cast?)

Console.ReadKey();
}
}
}

In above code am not able to assign the hashtable value to the new object created for my dll used in code.

My requirement is taking the objects in hashtable and at needed time i want to assign in other places example shown in above code.

Thanks,
S.Chand Basha

推荐答案

ADXVoice obj = (ADXVoice)objhashmap[key];


如果运行时类型与要转换为的类型赋值兼容,则可以这样做.在您的代码示例中,您显示了添加类型ADXVoice的值,因此对于该值,类型转换将成功.但是为什么要这样做?

不要使用那些过时的非通用(非专用)集合类型.使用例如System.Collections.Generic.Dictionary<int, ADXVoice>:
http://msdn.microsoft.com/en-us/library/xfhwa508%28v = vs.110%29.aspx [ ^ ].

您需要学习继承,编译时类型运行时类型以及其他基本的OOP思想以及泛型.

—SA


which is possible if runtime type is assignment-compatible with the type to be cast to. In your code sample, you show adding the value of the type ADXVoice, so, for this value, the typecast will be successful. But why doing so?

Don''t use those obsolete non-generic (non-specialized) collection types. Use, for example, System.Collections.Generic.Dictionary<int, ADXVoice>:
http://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx[^].

You need to learn inheritance, compile-time types vs runtime types and other basic OOP ideas, as well as generics.

—SA


这篇关于如何在C#中将对象分配给hastable值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-17 16:31