[英]C# Dictionary of classes with generic type
I'm trying to create a Genetic algorithm in C# but I want to separate the genes into classes (chromosomes)我正在尝试在 C# 中创建一个遗传算法,但我想将基因分成类(染色体)
basically I have a DNA class that is defined as基本上我有一个定义为的 DNA 类
public class DNA<T> { public T[] Genes { get; private set; } }
so I can have genes of type double, bool, int and etc...所以我可以拥有double、bool、int等类型的基因...
Then I want to define a chromosome as然后我想将染色体定义为
class Chromosome
{
Dictionary<string, DNA<T>> chromosomes;
}
So I would be able to add to the chromosome multiple DNA types like所以我可以将多种 DNA 类型添加到染色体中,例如
chromosomes.add("brain", new DNA<double>(...));
chromosomes.add("traits", new DNA<bool>(...));
chromosomes.add("body", new DNA<int>(...));
Should the dictionary value be object
or sould I create an IDNA
Interface to the DNA class to hold the object then cast it everytime I need?字典值应该是
object
还是应该创建一个到 DNA 类的IDNA
接口来保存对象,然后在每次需要时进行转换? Or there is an easier/best way to do that?或者有更简单/最好的方法来做到这一点? Thanks!
谢谢!
For multiple kind of genes as you wrote you could use interface/abstract class.对于您编写的多种基因,您可以使用接口/抽象类。
For data access instead of casting you can write a simple method GetDNAOfType
:对于数据访问而不是强制转换,您可以编写一个简单的方法
GetDNAOfType
:
using System;
using System.Collections.Generic;
using System.Linq;
public class Chromosome
{
Dictionary<string, DNA> chromosomes = new Dictionary<string, DNA>();
public IEnumerable<DNA<T>> GetDNAOfType<T>()
{
return chromosomes.Values.OfType<DNA<T>>();
}
public void AddDNA(string key, DNA dna)
{
if (chromosomes.ContainsKey(key))
chromosomes[key] = dna;
else
chromosomes.Add(key, dna);
}
}
public abstract class DNA
{
}
public class DNA<T> : DNA
{
public T[] Genes { get; private set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.