不同对象的C#数组 [英] C# array of different objects

查看:75
本文介绍了不同对象的C#数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个类B和D。我必须创建一个包含4个元素的数组,其中2个元素的类型为B,而2个元素的类型为D。我该怎么做?

  B o1 =新的B(); 
D o2 =新的D();
B o3 =新的B();
D o4 =新的D();

数组应该是这样的:

  array [0] = o1; array [1] = o2; array [2] = o3; array [3] = o4; 


解决方案

如果除对象之外没有其他通用基类,您只需要:

  object [] array = new object [4]; 
array [0] = o1;
//等

或一次性拍摄:

  object [] array = {o1,o2,o3,o4}; 

要使用特定于B或D的成员,需要在检索值时进行强制转换来自数组,例如

  B b =(B)array [0]; 
b.SomeMethodDeclaredOnB();

如果B和D具有 common 方法,则可以在这两个类都实现了该接口,并更改了数组的类型:

  IBD [] array = new IBD [4]; 
array [0] = o1;
...
array [0] .SomeMethodDeclaredInIBD();

或:

  IBD [] array = {o1,o2,o3,o4}; 
...
array [0] .SomeMethodDeclaredInIBD();

最后,要解决这个问题:


我是C#的新手。我不喜欢它,但我必须学习它。在PHP中,它要容易10000倍;


我敢肯定,如果我尝试使用PHP,我会发现完全相同的体验相反的方向。不要以为C#比PHP更糟糕或更难-只是不同而已,您一定会发现使用不熟悉的语言比舒适区语言更难。 p>

I have 2 classes B and D. I have to create an array with 4 elements 2 of type B and 2 of type D. How do I do it?

B o1 = new B();
D o2 = new D();
B o3 = new B();
D o4 = new D();

The array should be something like this:

array[0] = o1; array[1] = o2; array[2] = o3; array[3] = o4;

解决方案

If there is no common base class other than object, you just need:

object[] array = new object[4];
array[0] = o1;
// etc

Or in a single shot:

object[] array = { o1, o2, o3, o4 };

To use the members specific to B or D, you'd need to cast when you retrieved the values from the array, e.g.

B b = (B) array[0];
b.SomeMethodDeclaredOnB();

If B and D have common methods, you could declare those in an interface which both classes implemented, and change the type of the array:

IBD[] array = new IBD[4];
array[0] = o1;
...
array[0].SomeMethodDeclaredInIBD();

Or:

IBD[] array = { o1, o2, o3, o4 };
...
array[0].SomeMethodDeclaredInIBD();

Finally, to address this:

I am new to c#. I don't like it but I have to learn it. In PHP it's 10000 times easier;

I'm sure if I tried to use PHP I'd find the same experience in the exact opposite direction. Don't assume that C# is "worse" or "harder" than PHP - it's just different, and you're bound to find it harder to use a language you're not familiar with than your "comfort zone" language.

这篇关于不同对象的C#数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆