Change “ToString” for a sealed class

北城以北 提交于 2019-12-23 16:05:01

问题


I have a class I am working with:

public sealed class WorkItemType

It's ToString is weak (Just shows Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType).

Is there any way to override this to show the name of the WorkItemType?

Normally I would just aggregate the value in a new class, but I am using this for bindings in WPF (I want to have a list of WorkItemTypes in a combo box and assign the selected value to a bound WorkItemType variable.)

I think I am out of luck here, but I thought I would ask.


回答1:


Do you need to override ToString? If you are in control of the code where the object is displayed, you can always provide a FormatWorkItemType method, or something to that effect.




回答2:


A fairly neat way to do it might be to add an extenesion method to the WorkItemType object. Something like this:

public static class ToStringExtension
    {
        public static string MyToString(this WorkItemType w)
        {
           return "Some Stuff"
        }
    }

Then you could call something like

WorkItemType w = new WorkItemType;
Debug.WriteLine(w.MyToString();)



回答3:


You're out of luck :-(

You could write your own class that wraps the WorkItemType and delegate down to it (a proxy) expect for the ToString:

class MyWorkItemType
{
  private WorItemType _outer;

  public MyWorkItemType(WorkItemType outer)
  {
    _outer=outer;
  }

  public void DoAction()
  {
    _outer.DoAction();
  }

  // etc

  public override string ToString()
  {
    return "my value"
  }
}



回答4:


I don't have any C# knowledge, but can't you wrap your extended class inside another class? Proxy all method calls to the extended class, except toString(), Also very hackish, but I thought I'ld bring it up anyway.




回答5:


WPF provides a few different built-in ways to do this right in the UI. Two I'd recommend:

  • You can use ComboBox's DisplayMemberPath to display a single property value but still select from the WorkItemType objects.
  • If you want to display a composite of a few properties you can change the ComboBox's ItemTemplate to make it look pretty much however you want - formatting text, adding borders, colors, etc. You can even set up the DataTemplate to automatically be applied to any WorkItemType object that gets bound anywhere in your UI (same basic effect from UI perspective as changing ToString) by putting it into Resources and giving it only a DataType with no x:Key.



回答6:


Doing some sorta magic with reflection is probably your only hope. I know you can instantiate private constructors with it, so maybe you can override a sealed class... Note, this should be your last resort if there is seriously no other way. Using reflection is a very hackish/improper way of doing it.



来源:https://stackoverflow.com/questions/2120998/change-tostring-for-a-sealed-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!