c#字符串长度事件

时间:2016-09-28 22:01:28

标签: c#

基本上我想在字符串达到特定长度时启动一个事件。

我有一个静态字符串

Static String  _Info;

所以我的My Delegate有一个整数作为参数!

public Delegate void ReachLengthHandler(int Length);

和我的活动:

public event ReachLengthHandler ReachLengthEvent;

一种方法,一直向该字符串添加一些信息:

    public void AddInfo()
    {
     new Thread(() =>
    {
     while(true)
     _Info += ""; //Basically add the inputs of the user here ! 
     if (_Info.Length > 500)
      {
       if (ReachLengthEvent != null)
          ReachLengthEvent(_Info.Length);
      }
    }).Start();

    }

你认为它是正确的方式来做这个事件还是有更干净的方法?

编辑: 我想要这个事件,因为我想将这个字符串保存在数据库表行中,所以我不想扩展行的可能大小!

2 个答案:

答案 0 :(得分:1)

正如一些人在评论中指出的那样,你可能正试图解决XY Problem的一个实例 - 但假设你没有,你就不会以面向对象的方式接近事物,开始封装。

这可能是一个开始,FWIW:

public class MaxLengthEventArgs : EventArgs
{
    public MaxLengthEventArgs(string value)
    {
        LastAppended = value;
    }

    public string LastAppended { get; private set; }
}

public delegate void MaxLengthEventHandler(object sender, MaxLengthEventArgs args);

public class StringAccumulator
{
    protected StringBuilder Builder { get; private set; }

    public StringAccumulator(int maxLength)
    {
        if (maxLength < 0)
        {
            throw new ArgumentOutOfRangeException("maxLength", "must be positive");
        }
        Builder = new StringBuilder();
        MaxLength = maxLength;
    }

    public StringAccumulator Append(string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            var sofar = value.Length + Builder.Length;
            if (sofar <= MaxLength)
            {
                Builder.Append(value);
                if ((OnMaxLength != null) && (sofar == MaxLength))
                {
                    OnMaxLength(this, new MaxLengthEventArgs(value));
                }
            }
            else
            {
                throw new InvalidOperationException("overflow");
            }
        }
        return this;
    }

    public override string ToString()
    {
        return Builder.ToString();
    }

    public int MaxLength { get; private set; }

    public event MaxLengthEventHandler OnMaxLength;
}

class Program
{
    static void Test(object sender, MaxLengthEventArgs args)
    {
        var acc = (StringAccumulator)sender;
        Console.WriteLine(@"max length ({0}) reached with ""{1}"" : ""{2}""", acc.MaxLength, args.LastAppended, acc.ToString());
    }

    public static void Main(string[] args)
    {
        var acc = new StringAccumulator(10);
        try
        {
            acc.OnMaxLength += Test;
            acc.Append("abc");
            acc.Append("def");
            acc.Append("ghij");
            Console.WriteLine();
            acc.Append("ouch...");
            Console.WriteLine("(I won't show)");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.ReadKey();
    }
}

另外,请记住.NET中的字符串是不可变的。

使用字符串连接累积它们,就像在

中一样
_Info += ""

...不能很好地扩展(性能方面)。

&#39; HTH,

答案 1 :(得分:0)

通常,eventhandler与特定签名一起使用。

public delegate void ReachLengthHandler(object sender, EventArgs args);
class Program
{
    public event ReachLengthHandler handler;

    private const int Threshhold = 500;

    public string Info
    {
        set
        {
            if (value.Length > Threshhold)
            {
                this.OnReachLength(null);
            }
        }
    }

    public void OnReachLength(EventArgs args)
    {
        this.handler?.Invoke(this, args);
    }
}