简体   繁体   中英

How to replace c# ToString() method at runtime

How to implement an extension method that can change result of ToString() of any object?

What I have now:

public class ProxyBase
{
    public override string ToString()
    {
        return "hardcodedValue"
    }
}
public static T OverrideToString<T>(this T ob, message) where T : class
{
    var g = new ProxyGenerator();
    var o = new ProxyGenerationOptions();
    o.BaseTypeForInterfaceProxy = typeof(ProxyBase);
    // how to use message parameter here?
    return g.CreateInterfaceProxyWithTarget(ob, o);
}

I can't change the hardcodedValue at runtime

Here is the answer:

public class ProxyBase
{
    public string Message { get; set; }

    public override string ToString()
    {
        return Message;
    }
}

public static T OverrideToString<T>(this T ob, message) where T : class
{
    var g = new ProxyGenerator();
    var o = new ProxyGenerationOptions();
    o.BaseTypeForInterfaceProxy = typeof(ProxyBase);
    var proxied = g.CreateInterfaceProxyWithTarget(ob, o);
    var baseProxy = proxied as ProxyBase;
    baseProxy.Name = message;
    return proxied;
}

The main use case are parametrized XUnit test, where test runner uses default ToString() method for displaying parameters. When the parameter class is not from our code base and we can't inherit it, this extension may be used to give it a friendly name.

If you change the "hardcodedvalue" into a variable with onpropertychanged, you can set the variable and the ToString() will output different things.

     private string yourToStringResult
     public string YourToStringResult
     {
         get { return yourToStringResult; }
         set
         {
             yourToStringResult = value;
             OnPropertyChanged("YourToStringResult");
         }
     }

If you return YourToStringResult in your ToString, you can change the value that your ToString returns.

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