我的字节缓冲区Encoding.UTF8.GetString(b.Buffer)
的字符串表示是“Foo:Foo1”。
我想针对Regex解析字符串,然后使用类Message1
的2个不同属性(Message2
和RemoteData
)进行绑定。
public class RemoteData
{
private string _message1;
private string _message2;
public RemoteData(string Message1, string Message2)
{
this.Message1 = Message1;
this.Message2 = Message2;
}
public string Message1
{
get
{
if (IsValidMessage(_message1))
return _message1 = _message1.Split(':')[0].ToString();
return _message1;
}
set
{
_message1 = value;
}
}
public string Message2
{
get
{
if (IsValidMessage(_message2))
return _message2 = _message2.Split(':')[1].ToString();
return _message2;
}
set
{
_message2 = value;
}
}
private static bool IsValidMessage(string value)
{
const string expression = (@"([\w]+):([\w]+)");
return Regex.IsMatch(value, expression, RegexOptions.IgnoreCase);
}
}
我正在返回班级IObservable
的{{1}},以下代码正常运作。
RemoteData
问题:有没有办法,
public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint)
{
return Observable.Using(() => new UdpClient(endpoint),
udpClient => Observable.Defer(() =>
udpClient.ReceiveAsync().ToObservable()).Repeat().Select(b => new RemoteData(Encoding.UTF8.GetString(b.Buffer), Encoding.UTF8.GetString(b.Buffer))));
}
选择 Encoding.UTF8.GetString(b.Buffer)
?
Observable
的各种属性?谢谢!
答案 0 :(得分:1)
作为解决方案,我正在使用另一个类SplitData
并在RemoteData
构造函数中检查正则表达式。
public class SplitData
{
public string Message1 { get; set; }
public string Message2 { get; set; }
}
public class RemoteData
{
private SplitData _SplitData;
public RemoteData(string Message)
{
this.Message = Message;
if (IsValidMessage(this.Message))
{
_SplitData = new SplitData
{
Message1 = Message.Split(':')[0].ToString(),
Message2 = Message.Split(':')[1].ToString()
};
}
}
public string Message { get; }
public SplitData SplitData
{
get
{
return _SplitData;
}
set
{
_SplitData = value;
}
}
private static bool IsValidMessage(string value)
{
const string expression = (@"([\w]+):([\w]+)");
return Regex.IsMatch(value, expression, RegexOptions.IgnoreCase);
}
}
并将一个参数传递给UdpStream
方法,
public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint)
{
return Observable.Using(() => new UdpClient(endpoint),
udpClient => Observable.Defer(() =>
udpClient.ReceiveAsync().ToObservable()).Repeat().Select(b => new RemoteData(Encoding.UTF8.GetString(b.Buffer))));
}
如果有更好的方法,请告诉我。谢谢!