Best way to add boolean method to existing C # class
I'm sure this is a pretty simple task, but I'm not really sure how to write it into a search term. The best I got were extension methods and I couldn't understand them or get the syntax right.
I'm currently using a build that makes it easy to create mods for GTA V. These builds include Ped "type" with a bunch of related methods.
What I'm looking for is the ability to add my own method that can store the bool value as an extension to the Ped class.
Any help would be greatly appreciated, thanks.
source to share
You can use ConditionalWeakTable
for this task:
A
ConditionalWeakTable<TKey, TValue>
object is a dictionary that binds the managed object, which is represented by a key, to its attached property, which is represented by a value. The keys of the objects are individual instances of the TKey class to which the property is attached, and its values ββare the property values ββassigned to the corresponding objects.
Example:
public static class PedExtensions
{
private static readonly ConditionalWeakTable<Ped, PedProperties> _props = new ConditionalWeakTable<Ped, PedProperties>();
public static bool GetMyBool(this Ped ped)
{
return _props.GetOrCreateValue(ped).MyBool;
}
public static void SetMyBool(this Ped ped, bool value)
{
_props.GetOrCreateValue(ped).MyBool = value;
}
private class PedProperties
{
public bool MyBool { get; set; }
}
}
(You can of course make PedProperties
a top-level public class and expose that directly if you have a lot of properties to store).
Since the table uses weak references, you don't need to worry about memory leaks:
The class
ConditionalWeakTable<TKey, TValue>
differs from other collection objects in managing the lifetime of the keys of the keys stored in the collection. Usually, when an object is stored in a collection, its life cycle lasts until it is deleted (and there are no additional references to the object) or until the collection object itself is destroyed. However, in a class,ConditionalWeakTable<TKey, TValue>
adding a key / value pair to a table does not guarantee that the key will persist , even if it can be accessed directly from the value stored in the table (for For example, if the table contains one key,A
with a valueV1
and a second keyB
with a valueP2
that contains a link toA
). Instead of thisConditionalWeakTable<TKey, TValue>
automatically deletes a key / value entry as soon as no other key references exist outside of the table.
source to share
The correct answer is the one you already gave, extension methods.
public static class PedExtensions
{
public static bool CheckIfTrue(this Ped ped)
{
if(ped.something != "this value")
{
return true;
}
return false;
}
}
The "this" in the method signature refers to what the code is added to. so var myPed = new Ped (); myPed.CheckIfTrue (); will run the code in the extension.
source to share