简体   繁体   中英

Custom Class Converting in c#

I stuck converting class..

I have an arraylist that contains 4 different class which are not releated each other.

for example when user choose one like mylist[i], i should convert it, it's certain class and after can use .. i mean like

var type = mylist[i].GetType();

so now I have item's type. and when I create a variable as this type i mean like

var newItem = (type)mylist[i]

but type is not a class so then i cant convert it.

I am not sure if i am clear..

You can't cast to a variable - you have to explicitly state the type. You'll need to check for each class separately:

if(mylist[i] is FirstType)
{
    //do something
}
else if (mylist[i] is SecondType)
{
    //do something
}
//etc

A possibly better alternative would be to create 4 separate lists using List<T> and hold each type separately:

var firstList = new List<FirstType>();
var secondList = new List<SecondType>();
//etc

Or, if possible, create a base class if the data is similar enough and use a List<T> .

public class MyBase
{
    public int Id { get; set; }
}

public class FirstType : MyBase
{
}

public class SecondType : MyBase
{
}

var list = new List<MyBase>();
list.Add(new FirstType());
list.Add(new SecondType());

As mentioned in the comments, you can use partial classes to do this as well. They allow you to define a class in 2 or more files. For example, see how the Profile class you posted is defined as public partial class Profile : ProfileBase ? You can create your own file and define it again, with other interface implementations. For instance:

public interface IMyInterface
{
    public int Id { get; set; }
}

public partial class Profile : IMyInterface
{
    public int Id { get; set; }
}

This is a good overview on partial classes: http://msdn.microsoft.com/en-us/library/wa80x488.aspx

You can't cat to type defined at run time.

Assuming types you have are similar, but not related you can

  • use dynamic to switch to late binding. It will allow you to call methods you want at cost of compile type safety. "Duck typing" sample can be found in Duck type testing with C# 4 for dynamic objects
  • dynamically create methods that will do what you want with types defined at runtime via reflection or expression.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM