Change "ToString" to a private class

I have a class I'm working with:

public sealed class WorkItemType 

It ToString is weak (just showing Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType ).

Is there a way to override this to show the name WorkItemType ?

Usually I just collected the value in a new class, but I use this for bindings in WPF (I want to have the WorkItemTypes list in the combo box and assign the selected value to the WorkItemType variable.)

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

+4
source share
6 answers

Do you need to override ToString ? If you control the code where the object is displayed, you can always specify the FormatWorkItemType method or something like that.

+4
source

A fairly simple way to do this could be to add an extenesion method to the WorkItemType object. Something like that:

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

Then you can call something like

 WorkItemType w = new WorkItemType; Debug.WriteLine(w.MyToString();) 
+5
source

You were unlucky: - (

You can write your own class that wraps WorkItemType and delegates it (proxy) to 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" } } 
+2
source

I don't have any knowledge in C #, but can you wrap the extended class inside another class? Proxies all method calls for the extended class except toString() are also very hacks, but I thought I would raise it anyway.

+1
source

WPF provides several different built-in ways to do this directly in the user interface. Two I would recommend:

  • You can use the ComboBox DisplayMemberPath to display a single property value, but still select WorkItemType objects.
  • If you want to display a composition with several properties that you can change the ComboBox ItemTemplate to make it look pretty much the way you want it - text formatting, adding borders, colors, etc. You can even configure the DataTemplate to automatically apply to any WorkItemType object that binds anywhere in your user interface (the same basic effect of the user interface as changing ToString) by investing it in Resources and providing it only with a DataType without x: Key.
+1
source

Performing some kind of magic with reflection is probably your only hope. I know that you can create private constructors with it, so maybe you can override the private class ... Note: this should be your last resort, unless seriously there is no other way. Using reflection is a very hacky / wrong way to do this.

0
source

Source: https://habr.com/ru/post/1299161/


All Articles