我有一个对象需要通过网络使用TCP发送。我的工作正常,但我现在已经扩展了我的实现,并且无法确定如何定义我的FlatBuffer架构。
要发送的对象是:
public class Prediction
{
public PredictionMethod PredictionMethod { get; set; }
public NGramPrediction NGramPrediction { get; set; }
public DistancePrediction DistancePrediction { get; set; }
public int NGramOrder { get; set; }
}
PredictionMethod 是一个枚举:
public enum PredictionMethod
{
Distance = 1,
NGram = 2,
}
NGramPrediction 看起来像这样:
public class NGramPrediction
{
public KeyValuePair<char, int> Gram { get; set; }
public double Probability { get; set; }
public string Pattern { get; set; }
private int Total { get; set; }
private int Order { get; set; }
public NGramPrediction(Gram gram)
{
Total = gram.Total();
var orderedKeyPosibilities = gram.Posibilities.OrderByDescending(x => x.Value);
Gram = orderedKeyPosibilities.First();
Pattern = gram.Pattern;
Probability = (double)Gram.Value / Total;
Order = Pattern.Length;
}
}
Gram 看起来像这样:
public class Gram
{
public string Pattern { get; set; }
public Dictionary<char, int> Posibilities { get; set; }
public Gram(List<char> posibilities, int initialValue = 0)
{
Posibilities = new Dictionary<char, int>();
foreach (var posibility in posibilities)
{
Posibilities.Add(posibility, initialValue);
}
}
public int Total()
{
var keys = Posibilities.Keys;
var total = 0;
foreach (var key in keys)
{
var value = Posibilities[key];
total += value;
}
return total;
// return keys.Sum(key => Posibilities[key]);
}
}
DistancePrediction 如下所示:
public class DistancePrediction
{
public IIRVector3 Velocity { get; set; }
public float DeltaTime { get; set; }
public IIRVector3 Position { get; set; }
}
最后, IIRVector3 看起来像这样:
public class IIRVector3
{
public IIRVector3()
{
X = 0;
Y = 0;
Z = 0;
}
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
}
我试图为FlatBuffers定义我的架构:
enum FBPredictionMethod
{
Distance = 1,
NGram = 2
}
struct FBIIRVector3
{
X:float;
Y:float;
Z:float;
}
table FBDistancePrediction
{
Velocity:FBIIRVector3;
DeltaTime:float;
Position:FBIIRVector3;
}
table FBGram
{
Pattern:string;
Possibilities: ????
}
table FBNGramPrediction
{
Gram: ????
Probability:float;
Pattern:string;
Total:short;
Order:short;
}
table FBPrediction
{
PredictionMethod:FBPredictionMethod;
NGramPrediction:FBNGramPrediction;
DistancePrediction:FBDistancePrediction;
NGramOrder:short;
}
root_type FlatServerToClientMessage;
我认为一切看起来都是正确的,但我不知道该为字典做些什么......
FBGram.Possibilities 应为Dictionary<char, int>
, FBGram 应为KeyValuePair<char, int>
。
注意: Gram的构造函数将List<char>
和int
作为参数,而NGramPrediction
的构造函数则需要Gram
}作为参数。
有人可以帮我解决我的架构吗?
答案 0 :(得分:2)
KeyValuePair
应该很简单..要么只是将它们存储为两个单独的字段,要么使用struct KeyValuePair { key:byte; value:int; }
Dictionary
可以存储为Possibilities:[KeyValuePair]
(使用相同的结构)。如果您想在Possibilities
可能很大的情况下节省空间,那么PossibilityKeys:[byte]
和PossibilityValues:[int]
会更紧凑,但更难读/写。