简体   繁体   English

C#-创建类似ToString()的函数

[英]C# - create function like ToString()

I want to create function, the function name is extend() ,it should after the string,bool,control.like default function ToString() 我想创建一个函数,函数名是extend(),它应该在字符串,布尔值,控件之后。比如默认函数ToString()

"123".extend();
false.extend();
textbox1.extend();
extend();

The extend() function can check the input type extend()函数可以检查输入类型

if input is string ? ToUpperCase , Substring and Replace the string
if input is bool ? checking the bool 
if input is Control ? check control type , change text,color 
if input is List ? to update global list

And get property name to do something 并获取属性名称以执行某项操作

string SaveString ="";
SaveString.extend();

if(propertyname(object) =="SaveString"){
}

How can i create a function like this ?Thanks 我如何创建这样的功能?谢谢

Use Extension Methods 使用扩展方法

namespace System
{
    public static class ObjectExtension
    {
        public static string Extend(this object input)
        {
            // Do something to input object.
            // For example, you can have different implementation based on its type.

            if (input is string)
            {
            }
            else if (input is bool)
            {
            }
        }
    }
}

There will be no performance penalty while using extension methods on object, because it's compiler feature, see C# Extension Method for Object 在对象上使用扩展方法时, 不会有性能损失,因为它具有编译器功能,请参阅对象的C#扩展方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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