|
Given the following code:
public class Employee1
{
public string Property1 { get; set; }
public Employee1() {}
}
public class Employee2:Employee1
{
public string Property2 { get; set; }
public Employee2():base() {}
}
public class Form1
{
List<employee1> m_employees = new List<employee1>();
private void Add()
{
m_employees.Add(new Employee1());
m_employees.Add(new Employee2());
}
private bool IsType(object item, string typeName)
{
bool result = false;
if (item != null && !string.IsNullOrEmpty(typeName))
{
result = (item.GetType().Name == typeName);
}
return result;
}
}
I want to add the items in this list to a ListView , but I have to cast the objects to their actual types, like so:
string[] listItems = new string[2];
if (IsType(obj, "Employee2"))
{
listItems[0] = ((Employee2)obj).Property1;
listItems[1] = ((Employee2)obj).Property2;
}
else
{
listItems[0] = ((Employee1)obj).Property1;
listItems[1] = "Not applicable";
}
I want something more generic (I want to avoid using the actual type names if possible). I tried to use various properties in the type object returned by Type.GetType("Employee2", true, false); as a casting mechanism, but nothing seems to work.
I want to do something like this:
string[] listItems = new string[2];
Type itemType = obj.GetType();
listItems[0] = (itemType)obj).Property1;
if (IsType(obj, "Employee2"))
{
listItems[1] = ((itemType)obj).Property2;
}
else
{
listItems[1] = "Not applicable";
}
Does anyone have any ideas?
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
|
|
|
|
|
John Simmons / outlaw programmer wrote:
Does anyone have any ideas?
Usually, you do something like this:
Employee2 empl = null;
if (obj is Employee2)
empl = (Employee2)obj;
or you can do this:
Employee2 empl = obj as Employee2;
The latter will return null if obj is not of type Employee2 ;
regards
modified 12-Sep-18 21:01pm.
|
|
|
|
|
I'm already doing that, and that's what I want to avoid.
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
|
|
|
|
|
Ah, now I understand what you're trying to do.
In this case I don't think you get around some mapping mechanism and reflection, something like (defined in a XML file or whatever):
"Employee2" -> Property1 x Property2
But that still requires some knowledge about the types and properties being used.
Maybe you can use attributes and reflection to get a list of all the necessary properties to take into account when adding them to the listview. Something like this:
[ListViewProps("Propery1", "Not Applicable")]
class Employee1
{
}
[ListViewProps("Propery1", "Property2")]
class Employee2
{
}
And then doing some reflection magic to automatically get the values of the properties
modified 12-Sep-18 21:01pm.
|
|
|
|
|
Not a answer to your exact question, but when I've needed to do this before I add a ToListViewItem() method in the class so each class can do it's thing seperately.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Sounds like a good solution, although it couples GUI logic with the business logic. I don't think an Employee object should know anything about a ListView
modified 12-Sep-18 21:01pm.
|
|
|
|
|
I agree, but... it's not coupling to the actual ListView, just returning a ListViewItem so it can be dropped into a ListView easily by the presentation layer. Not ideal, but functional.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
I also still have to cast it to the specific type. :/
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
|
|
|
|
|
Hmmm, good idea. It definitely reduced the amount of code in the form. Instead of creating a ListViewItem object, though, I returned a string array so that using the class doesn't require any more dependencies than necessary (so my method name is actually ToStringArray() .
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
|
|
|
|
|
I thing the ToXXXArray method is probably the best way John, but I had another obvious thought this morning. You could use an IEmployee interface with the two properties, and in Employee1 either throw a NotImplementedException (and catch it when building the list - I hate throwing exceptions personally ) or return String.Empty / "Not applicable" for the unused property.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
DaveyM69 wrote: either throw a NotImplementedException
Nah - ugly is as ugly does.
DaveyM69 wrote: or return String.Empty / "Not applicable" for the unused property.
I don't want to introduce interfaces to the group yet. We're training up our COBOL programmers so they can move to .Net/C# with the rest of the dev team via in-house training provided by the experienced .Net programmers we already have (there are four of us, and about a dozen of "them").
I'm giving this week's class, and am recapping what they learned over the last couple of weeks because I want to make sure they understand the fundamentals before we move on. Last week, they were introduced to OOP principals, and given a homework assignment to build an Employee class. They were told about inheritance, encapsulation, and polymorphism, but were not given real examples of those things. I'm starting with their homework assignment from last week, and using a 4-step solution to fully illustrate those concepts.
I don't fully understand interfaces and why they're used yet, but it seems to me that using an interface isn't appropriate because it destroys the object-oriented aspect of the code. (Don't forget, I'm a C++ guy at heart.) Can you give me an example of how an interface would be implemented/used in this particular case?
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
|
|
|
|
|
John Simmons / outlaw programmer wrote: Can you give me an example
Sure... I'll just post working code. Just ask if more clarification is needed, but I think it should make sense.
namespace EmployeeTestApp
{
public interface IEmployee
{
string Property1
{
get;
set;
}
string Property2
{
get;
set;
}
}
}
namespace EmployeeTestApp
{
public class Employee1 : IEmployee
{
private string m_Property1;
private string m_Property2;
public Employee1()
: this("Unknown")
{ }
public Employee1(string property1)
{
m_Property1 = property1;
m_Property2 = "Not applicable";
}
#region IEmployee Members
public string Property1
{
get { return m_Property1; }
set
{
if (m_Property1 != value)
{
m_Property1 = value;
}
}
}
public string Property2
{
get { return m_Property2; }
set
{
}
}
#endregion
}
}
namespace EmployeeTestApp
{
public class Employee2 : IEmployee
{
private string m_Property1;
private string m_Property2;
public Employee2()
: this("Unknown", "Unknown")
{ }
public Employee2(string property1, string property2)
{
m_Property1 = property1;
m_Property2 = property2;
}
#region IEmployee Members
public string Property1
{
get { return m_Property1; }
set
{
if (m_Property1 != value)
{
m_Property1 = value;
}
}
}
public string Property2
{
get { return m_Property2; }
set
{
if (m_Property2 != value)
{
m_Property2 = value;
}
}
}
#endregion
}
}
using System.Collections.Generic;
using System.Windows.Forms;
namespace EmployeeTestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<IEmployee> employees = new List<IEmployee>();
employees.Add(new Employee1(
"Employee1 Instance, Property1"));
employees.Add(new Employee2(
"Employee2 Instance, Property1", "Property2"));
foreach(IEmployee employee in employees)
{
ListViewItem item = new ListViewItem(employee.Property1);
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
subItem.Text = employee.Property2;
item.SubItems.Add(subItem);
listView1.Items.Add(item);
}
}
}
}
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
But Employee1 has a property, and Employee2 is derived from Employee1 and has a property that Employee1 doesn't have. How is an interface going to help in that case?
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
|
|
|
|
|
It doesn't help as such as in the example I gave, it forces Employee1 to implement Property2, but in its implementation it returns simply "Not Applicable". As I said previously, it should really throw a NotImplementedException so:
get { throw new NotImplementedException("Not Applicable"); } and
try
{
subItem.Text = employee.Property2;
}
catch (NotImplementedException ex)
{
subItem.Text = ex.Message;
} The advantage is it gives you a common minimum implementation for all possible employee classes so you can treat all employee classes as equal for list building etc. Very similar to having an abstract base class but without providing any base implementation.
I suppose the interface should only have Property1, but then it wouldn't be any use in your situation.
Another alternative option I suppose is to provide a ToEmployee2() method in Employee1, but that seems wrong as you're coupling the two classes together and Employee1 is an Employee1, NOT an Employee2. That's why I prefer to use an interface rather than deriving from another similar class, unless it's definately a 'extended' version (EmployeeEx) of the base, in which case I wouldn't be showing the extended properties in the ListView as it's a list of Employee properties, not EmployeeEx.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
John Simmons / outlaw programmer wrote: isn't appropriate because it destroys the object-oriented aspect of the code
No, and that's the point of them in many cases as the interface isn't an object. When building a list of IEmployee, were still using the actual Employee1 and Employee2 instances, but restricting ourselves to using only properties/methods that are declared in the interface, which is exactly what you want if you need a list of all employees regardless of the actual class.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
OK, I'm gonna shut up after this post!
Maybe not suitable for your exact 'teaching' situation, but the easy way to solve this is an implicit conversion operator in the Employee1 class:
public static implicit operator Employee2(Employee1 value)
{
return new Employee2(value.Property1, "Not Applicable");
} Now, you can just build your list of Employee2's using either Employee1's or Employee2's.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Hi;
One have questions....
Before I'm english not great..Sorry;
Create in a Runtime have Labels...
I have total 24 Labels.But I am Six array one under the other...
Exam;
Lbl 1 Lbl 2 Lbl 3 Lbl 4 Lbl 5 Lbl 6
Lbl 7 Lbl 8 Lbl 9 Lbl 10Lbl 11Lbl 12.....Such as....
Now.. I am Random number to allure and Says: İf lbl.text properts with Random Number balanced.Doing Lbl.Enabled==false;
I am Actual Ques that....
if One Array all Lbl Enabled Properts false.MsgBox showing...
How To This Problem....
|
|
|
|
|
I am sorry, but your english is so bad that I can't understand what you are trying to ask for...
Perhaps if you posted some of your code, there would at least be a starting point.
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
ı am Very very sorry
>NOw..
private void KartOlustur()
{
for (int i = 1; i <= 24; i++)
{
Label l = new Label();
l.Top = yukardan;
l.Left = soldan;
l.Height = 30;
l.Width = 30;
soldan += 30;
l.BorderStyle = BorderStyle.FixedSingle;
l.BackColor = Color.Aqua;
l.ForeColor = Color.Gray;
this.Controls.Add(l);
if (i % 6 == 0)
{
soldan = 25;
yukardan += 30;
}
for (int a = 0; a < tombala.Length; a++)
{
do
{
GelenSayi = RastgeleSayi.Next(1, 90);
SayiVar = false;
for (int w = 0; w < tombala.Length; w++)
{
if (GelenSayi == tombala[w])
{
SayiVar = true; break;
}
}
} while (SayiVar == true);
tombala[a] = GelenSayi;
for (int u = 0; u < this.Controls.Count; u++)
{
if (this.Controls[u] is Label)
{
this.Controls[u].Name = tombala[a].ToString();
}
}
}
l.Text = l.Name;
}
Random cekilensayi = new Random();
int gelen = cekilensayi.Next(1, 90);
bool FalSemi;
foreach (Control item in this.Controls)
{
if (item is Label && item.Text == gelen.ToString())
{
item.Enabled = false;
}
I am creating array in label at.
İF one dozen in label Enabled propery==false.
Showing MsgBox...
ı hope your understand problem me...
Thanks...
|
|
|
|
|
I don't know exactly what you are trying to do in this code:
for (int a = 0; a < tombala.Length; a++)
{
do
{
GelenSayi = RastgeleSayi.Next(1, 90);
SayiVar = false;
for (int w = 0; w < tombala.Length; w++)
{
if (GelenSayi == tombala[w])
{
SayiVar = true; break;
}
}
} while (SayiVar == true);
tombala[a] = GelenSayi;
for (int u = 0; u < this.Controls.Count; u++)
{
if (this.Controls[u] is Label)
{
this.Controls[u].Name = tombala[a].ToString();
}
}
}
l.Text = l.Name;
but all that code can be replaced with just this:
l.Text = RastgeleSayi.Next(1, 90).ToString();
This is what I guess you are trying to do. It picks a winning number, then 24 numbers to display as labels. If the winning number is among the 24, that label is disabled.
Random rnd = new Random();
int winner = rnd.Next(1, 90);
int[] numbers = new int[24];
for (int i = 0; i < 24; i++) {
int number;
bool done;
do {
number = rnd.Next(1, 90);
done = true;
for (int j = 0; j < i; j++) {
if (number == numbers[j]) {
done = false;
break;
}
}
} while (!done);
numbers[i] = number;
Label l = new Label();
l.Top = 25 + (i / 6) * 30;
l.Left = 25 + (i % 6) * 30;
l.Text = number.ToString();
l.Width = 30;
l.Height = 30;
l.BorderStyle = BorderStyle.FixedSingle;
l.BackColor = Color.Aqua;
l.ForeColor = Color.Gray;
l.Enabled = (number != winner);
this.Controls.Add(l);
}
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
very thanks to answer....
but problem so Form on Creating Labels.If One sequence Labels Property ==False Showing MsgBox...
Example
>http://img99.imageshack.us/img99/3963/form1bq1.png
Pls Looking at the picture..there to be button its Click Execute this code...
int gelen = cekilensayi.Next(1, 90);
foreach (Control item in this.Controls)
{
if (item is Label && item.Text == gelen.ToString())
{
item.Enabled = false;
}
Okey! ı am says: If it Picture in black Checked all labels Enabled==false
Showing MsgBox...
Very Thanks to Answer ....Very Thanks...
|
|
|
|
|
As the numbers picked in the 24 labels are unique, there can't be any number that matches more than one of the labels. Do you have more than one winning number to check for?
When checking numbers, don't loop through the labels to find the numbers. Keep the array of numbers from when you created the labels. To access the label associated with each number you can create an array of labels to store the reference to each label in.
To check for rows of mathcing numbers, you can use an array where you count the matching numbers in each row:
int[] rows = new int[4];
foreach (int winningNumber in winningNumbers) {
for (int i = 0; i < 24; i++) {
if (number[i] == winningNumber) {
rows[i / 6]++;
break;
}
}
}
for (int i = 0; i < 4; i++) {
if (rows[i] == 6) {
MessageBox.Show(String.Format("Row #{0} is full.", i + 1));
}
}
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
hi all!help needed..!!!
any idea about the source code for retrieving a song from the database by either humming the tune or giving voice commands as input..!!!
|
|
|
|
|
|
but how to differentiate between male and female voice..???
|
|
|
|