这是一个属性,其值是根据给定的属性/值计算的。我希望我能正确理解您的要求。让我知道它是否不符合您的需要。我也尝试写尽可能多的 cmets。所以让代码来说话吧:)
public class Sample {
/// <summary>
/// This sourcestring is set to the same value of Sample with Id = 1
/// </summary>
private string _sourceStringOfSampleWithId1;
/// <summary>
/// Creates a Sample instance
/// </summary>
/// <param name="id">Id of Sample</param>
/// <param name="source">Source of Sample</param>
public Sample(int id, string source) {
Id = id;
Source = Source;
}
/// <summary>
/// Id of Sample
/// </summary>
public int Id { get; }
/// <summary>
/// Source of Sample
/// </summary>
public string Source { get; }
/// <summary>
/// Calculative property for CharRatio
/// </summary>
public double CharRatio => (double)_sourceStringOfSampleWithId1.Length / Source.Length * 100;
/// <summary>
/// Sets SourceString of Sample with Id = 1
/// </summary>
/// <param name="sourceString"></param>
public void SetSourceString(string sourceString) {
_sourceStringOfSampleWithId1 = sourceString;
}
}
这是你如何使用它:
List<Sample> sampleList = new List<Sample>(); // Creates a sample list
sampleList.Add(new Sample(1, "source")); //id 1 is always source charRatio 100 since 6/6 in percentage
sampleList.Add(new Sample(2, "test")); //charRatio = 66
sampleList.Add(new Sample(3, "test")); //charRatio = 66
sampleList.Add(new Sample(4, "test")); //charRatio = 66
var sampleWithId1 = sampleList.Find(s=>s.Id == 1); // Find sample with Id = 1
sampleList.ForEach(s=>s.SetSourceString(sampleWithId1.Source)); // Set all samples calcualtive source string to Sample with Id =1
var ratio = sampleList[2].CharRatio; //66.66; // Get an example from list and see char ratio
基于 cmets,这里是 Sample 类的编辑版本。我也保留原来的答案。因此,请使用适合您的用例的任何一个。我不会评论这种情况,因为从原始答案中应该很明显。
public class SampleWithStaticField {
private static string _sourceStringOfSampleWithId1;
public SampleWithStaticField(int id, string source) {
Id = id;
Source = Source;
// Set static source string which will be shared between all instances
if(Id == 1) {
_sourceStringOfSampleWithId1 = source;
}
}
public int Id { get; }
public string Source { get; }
public double CharRatio {
get {
if(_sourceStringOfSampleWithId1 == null) {
throw new Exception($"{nameof(_sourceStringOfSampleWithId1)} is not set!");
}
return (double)_sourceStringOfSampleWithId1.Length / Source.Length * 100;
}
}
}
这里是你如何使用它
var sampleList = new List<Sample>();
sampleList.Add(new Sample(1, "source")); //id 1 is always source charRatio 100 since 6/6 in percentage
sampleList.Add(new Sample(2, "test")); //charRatio = 66
sampleList.Add(new Sample(3, "test")); //charRatio = 66
sampleList.Add(new Sample(4, "test")); //charRatio = 66
var ratio = sampleList[2].CharRatio; //66.66;