简体   繁体   中英

Can C# make my class look like another class?

I have a class that looks like this:

public class BasePadWI
{
    public WorkItem WorkItemReference { get; set; }
    .... Other stuff ......
}

I then have a dictionary that is defined like this:

public Dictionary<BasePadWI, Canvas> Pad { get; set; }

I would then like to make a call like this:

List<WorkItem> workItems = Pad.Keys.ToList();

(Note: WorkItem is a sealed class, so I cannot inherit.)

Is there some trickery that I could do in the class to make it look like a WorkItem ?

I have done this in the meantime:

List<WorkItem> workItems = Pad.Keys.ToList().ConvertAll(x=>x.WorkItemReference );

You can do:

List<WorkItem> workItems = Pad
                             .Keys
                             .Select(basePad => basePad.WorkItemReference)
                             .ToList();

This uses LINQ to extract out your member on the fly.

You can override the cast operator for

public class BasePadWI
{
    protected WorkItem _workItemReference;
    public WorkItem WorkItemReference { get { return _workItemReference; }}


    public static implicit operator WorkItemReference(BasePadWI item)
    {
       return item._workItemReference;
     }
    .... Other stuff ......
}

This might be a little misleading since you're not really casting BasePadWI to WorkItem, but it should let you build the lists you want quite easily.

Whenever you do do something like the following:

BasePadWI bpw = new BasePadWI();

WorkItem item = bpw;

bpw should be implicitly converted to a WorkItem, which, due to the operator we've declared, returns a reference to bpw's internal WorkItem _workItemReference.

You can also use this to, say, cast database connections to integers, so be careful that you don't make your code too difficult to interpret by the poor schmuck who's going to wind up maintaining this later.

No. A BasePadWI is not a WorkItem. If you want the benefits of inheritance, then you need to use inheritance. In your case, you'd need to make BasePadWI inherit from WorkItem. The ConvertAll is about as good as you can do without unsealing WorkItem.

Overriding the cast operator is possible. I see David has just posted the same. Here is a sample.

   class Program
   {
      static void Main(string[] args)
      {
         Foo foo = new Foo();
         BasePadWI bp = (BasePadWI)foo;
         Console.WriteLine(bp.name);
      }
   }

   class BasePadWI {
      public string name = "BasePadWI";
   }

   class Foo
   {
      BasePadWI basePadWI = new BasePadWI();

      public static implicit operator BasePadWI(Foo foo)
      {
         System.Console.WriteLine("Converted Foo to BasePadWI");
         return foo.basePadWI;
      }
   }

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