gd_core/addons/core/misc/Test.cs

63 lines
2.1 KiB
C#

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// D E R E L I C T
//
/// // (c) 2003..2024
/*
So, someone on the Godot.CSharp channel asked about a generic way to do covariant style (I think its covariant) code for running a different function per type
I wrote a way to do it using static lambdas on a generic class, and realized I could do a trait style system with it.
Going to have to investigate it a bit further to see if it would make some code easier.
*/
using Godot;
using System;
namespace dbg;
public class GenericSetText
{
static public void SetText<T>( T v, string text ) => GenericSetText<T>.FnSetText( v, text );
}
public class GenericSetText<T>
{
static public Action<T, string> FnSetText = ( v, s ) => GD.PrintErr( $"On {typeof( T ).Name} trying to SetText" );
static public void SetText( T v, string text ) => GenericSetText<T>.FnSetText( v, text );
}
static public class GenericTest
{
static GenericTest()
{
GenericSetText<Control>.FnSetText = ( label, s ) =>
{
var type = typeof( GenericSetText<> ).MakeGenericType( label.GetType() );
var method = type.GetMethod( "SetText", 1, new Type[1] { label.GetType() } );
method.Invoke( label, new object[1] { s } );
};
GenericSetText<Label>.FnSetText = ( label, s ) => label.Text = s;
GenericSetText<Button>.FnSetText = ( button, s ) => button.Text = s;
GenericSetText<TextEdit>.FnSetText = ( textEdit, s ) => textEdit.Text = s;
GenericSetText<RichTextLabel>.FnSetText = ( richText, s ) => richText.Text = s;
GenericSetText<string>.FnSetText = ( v, s ) => { };
}
static public void RunTests()
{
Control controlTest = new Button();
GenericSetText.SetText( controlTest, "Button text" );
Button buttonTest = new();
GenericSetText.SetText( buttonTest, "Button text" );
Label labelTest = new();
GenericSetText.SetText( labelTest, "Label Text" );
TextEdit textEditTest = new();
GenericSetText.SetText( textEditTest, "Label Text" );
int integerTest = 10;
GenericSetText.SetText( integerTest, "Integer Test" );
}
}