我第一次看到一位同事在实施对象池时这样做了.他将要作为参数汇集的类传递给泛型基类.这个基类列出了池代码.
奇怪的是基类会知道它的孩子.在每种正常情况下,这被认为是不好的做法.但在这种情况下,父母只是避免编写重复代码的技术解决方案.任何其他代码都不会引用基类.
这种结构的一个缺点是它"烧掉了基础类".您不能在层次结构的中间引入通用基类.此问题可能超出了主题范围.
以下是一个可以想象的例子:
public abstract class Singleton<T> where T : class
{
public static T Instance { get; private set; }
public Singleton()
{
if (Instance != null)
throw new Exception("Singleton instance already created.");
Instance = (T) (object) this;
}
}
public class MyClass : Singleton<MyClass>
{
}
Run Code Online (Sandbox Code Playgroud)
改进代码:
public abstract class Singleton<T> where T : Singleton<T>
{
public static T Instance { get; private set; }
public Singleton()
{
if (Instance != null)
throw new Exception("Singleton instance already …Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,我将日志字符串保存在循环缓冲区中.当日志变满时,对于每个新插入,旧的字符串将被释放用于垃圾收集,然后它们在第2代内存中.因此,最终将发生第2代GC,我想避免.
我试图将字符串编组成一个结构.令人惊讶的是,我仍然得到第2代GC:s.结构似乎仍然保留了对字符串的引用.完整的控制台应用程序 任何帮助赞赏.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct FixedString
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
private string str;
public FixedString(string str)
{
this.str = str;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct UTF8PackedString
{
private int length;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
private byte[] str;
public UTF8PackedString(int length)
{
this.length = length;
str = new byte[length];
}
public static implicit operator UTF8PackedString(string str)
{
var obj …Run Code Online (Sandbox Code Playgroud)