Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

Type d'un objet

6 réponses
Avatar
J-L
Bonjour,

Je récupère dans une variable de type object des valeurs de types
divers dans la base de registre.

Est-ce qu'il y a une possibilité de connaitre le type de cette valeur à
partir de l'objet et faire un switch selon le type trouvé ?

J-L

6 réponses

Avatar
Agnain
J-L a écrit :
Bonjour,

Je récupère dans une variable de type object des valeurs de types divers
dans la base de registre.

Est-ce qu'il y a une possibilité de connaitre le type de cette valeur à
partir de l'objet et faire un switch selon le type trouvé ?

J-L





Bonjour,

oui et non.

Non parce que vérifier un type se fait avec l'opérateur is :
if (monobjet is string)

oui parce qu'il est possible de récupérer le nom du type dans une chaîne :
string type = monobjet.GetType().Fullname;
switch (type)
{
case "System.String":
// Hop
break;
}
Avatar
J-L
>
oui parce qu'il est possible de récupérer le nom du type dans une chaîne :
string type = monobjet.GetType().Fullname;
switch (type)
{
case "System.String":
// Hop
break;
}




Bon , c'est un peu ce que je fais pour l'instant. En fait, je suis
confronté à des erreurs de type sur les propriétés d'une classe.
Je suis obligé de faire comme ça:

try
{
if (propertyInfo.PropertyType.Name == "DBMSTypes")
{
string valuestr = value.ToString();
Cube_database.DBMSTypes dbtype =
(Cube_database.DBMSTypes)Enum.Parse(typeof(Cube_database.DBMSTypes),
valuestr);
propertyInfo.SetValue(this, dbtype, null);
}
if (propertyInfo.PropertyType.Name == "String")
{
propertyInfo.SetValue(this, value.ToString(), null);
}
if (propertyInfo.PropertyType.Name == "Boolean")
{
propertyInfo.SetValue(this, Convert.ToBoolean(value), null);
}
if (propertyInfo.PropertyType.Name == "Int32")
{
propertyInfo.SetValue(this, Convert.ToInt32(value), null);
}
}
catch (Exception exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}

Dans le code ci-dessus, value est un object récupéré dans la base de
registre. Si je fais directement:

propertyInfo.SetValue(this, value, null);

J'ai plein d'erreur de cast.

C'est normal ou je me suis gourré kekpart ?

J-L
Avatar
Agnain
J-L a écrit :

oui parce qu'il est possible de récupérer le nom du type dans une
chaîne :
string type = monobjet.GetType().Fullname;
switch (type)
{
case "System.String":
// Hop
break;
}




Bon , c'est un peu ce que je fais pour l'instant. En fait, je suis
confronté à des erreurs de type sur les propriétés d'une classe.
Je suis obligé de faire comme ça:

try
{
if (propertyInfo.PropertyType.Name == "DBMSTypes")
{
string valuestr = value.ToString();
Cube_database.DBMSTypes dbtype =
(Cube_database.DBMSTypes)Enum.Parse(typeof(Cube_database.DBMSTypes),
valuestr);
propertyInfo.SetValue(this, dbtype, null);
}
if (propertyInfo.PropertyType.Name == "String")
{
propertyInfo.SetValue(this, value.ToString(), null);
}
if (propertyInfo.PropertyType.Name == "Boolean")
{
propertyInfo.SetValue(this, Convert.ToBoolean(value), null);
}
if (propertyInfo.PropertyType.Name == "Int32")
{
propertyInfo.SetValue(this, Convert.ToInt32(value), null);
}
}
catch (Exception exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}

Dans le code ci-dessus, value est un object récupéré dans la base de
registre. Si je fais directement:

propertyInfo.SetValue(this, value, null);

J'ai plein d'erreur de cast.

C'est normal ou je me suis gourré kekpart ?

J-L





J'ai besoin de plus d'infos, notamment à propos de propertyInfo. C'est
le PropertyInfo de quelle propriété ? Quel est son type réel, object,
inconnu car défini dans une classe dérivée ?
Avatar
J-L
Les propriétés sont dans une classe parente Settings avec leur
description sous forme d'attributs.
La classe enfant SettingsREG lit et enregistre les settings dansla base
de registre.

public class SettingsREG : Settings


private void LoadOrSave(IOSettings settingsIO)
{
PropertyInfo[] propertiesinfo = this.GetType().GetProperties();
object[] attributes = null;
foreach (PropertyInfo propertyInfo in propertiesinfo)
{
if (propertyInfo.IsDefined(typeof(ParameterAttribute), false))
{
// Get the type and PropertyInfo.
attributes = propertyInfo.GetCustomAttributes(true);
foreach (Attribute attribute in attributes)
{
if (attribute is ParameterAttribute)
{
// Read ParameterAttribute info
ParameterAttribute attr =
(ParameterAttribute)attribute;
if (settingsIO == IOSettings.LoadSettings)
{
RegistryToProperty(attr, propertyInfo);
}
else if (settingsIO == IOSettings.SaveSettings)
{
PropertyToRegistry(attr, propertyInfo);
}
}
}
}
}


private void RegistryToProperty(ParameterAttribute parameterAttribute,
PropertyInfo propertyInfo)
{

string keyname = pathreg + parameterAttribute.Category;
object value = null;

if (propertyInfo != null)
{
switch (parameterAttribute.RegistryKey)
{
case RegistryKeys.rkUser:
value =
RegistryAccess.GetValue(KeyType.HKEY_CURRENT_USER, keyname,
parameterAttribute.Name);
break;
case RegistryKeys.rkLocalMachine:
value =
RegistryAccess.GetValue(KeyType.HKEY_LOCAL_MACHINE, keyname,
parameterAttribute.Name);
break;
default:
break;
}
try
{
if (propertyInfo.PropertyType.Name == "DBMSTypes")
{
string valuestr = value.ToString();
Cube_database.DBMSTypes dbtype =
(Cube_database.DBMSTypes)Enum.Parse(typeof(Cube_database.DBMSTypes),
valuestr);
propertyInfo.SetValue(this, dbtype, null);
}
else if (propertyInfo.PropertyType.Name == "String")
{
propertyInfo.SetValue(this, value.ToString(), null);
}
else if (propertyInfo.PropertyType.Name == "Boolean")
{
propertyInfo.SetValue(this, Convert.ToBoolean(value),
null);
}
else if (propertyInfo.PropertyType.Name == "Int32")
{
propertyInfo.SetValue(this, Convert.ToInt32(value),
null);
}
}
catch (Exception exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
}


Dans le code ci-dessus, RegistryAccess.GetValue renvoie un object lue
dans une valeur de la base registre.
Avatar
Agnain
J-L a écrit :
Les propriétés sont dans une classe parente Settings avec leur
description sous forme d'attributs.
La classe enfant SettingsREG lit et enregistre les settings dansla base
de registre.

public class SettingsREG : Settings


private void LoadOrSave(IOSettings settingsIO)
{
PropertyInfo[] propertiesinfo = this.GetType().GetProperties();
object[] attributes = null;
foreach (PropertyInfo propertyInfo in propertiesinfo)
{
if (propertyInfo.IsDefined(typeof(ParameterAttribute), false))
{
// Get the type and PropertyInfo.
attributes = propertyInfo.GetCustomAttributes(true);
foreach (Attribute attribute in attributes)
{
if (attribute is ParameterAttribute)
{
// Read ParameterAttribute info
ParameterAttribute attr = (ParameterAttribute)attribute;
if (settingsIO == IOSettings.LoadSettings)
{
RegistryToProperty(attr, propertyInfo);
}
else if (settingsIO == IOSettings.SaveSettings)
{
PropertyToRegistry(attr, propertyInfo);
}
}
}
}
}


private void RegistryToProperty(ParameterAttribute parameterAttribute,
PropertyInfo propertyInfo)
{

string keyname = pathreg + parameterAttribute.Category;
object value = null;

if (propertyInfo != null)
{
switch (parameterAttribute.RegistryKey)
{
case RegistryKeys.rkUser:
value =
RegistryAccess.GetValue(KeyType.HKEY_CURRENT_USER, keyname,
parameterAttribute.Name);
break;
case RegistryKeys.rkLocalMachine:
value =
RegistryAccess.GetValue(KeyType.HKEY_LOCAL_MACHINE, keyname,
parameterAttribute.Name);
break;
default:
break;
}
try
{
if (propertyInfo.PropertyType.Name == "DBMSTypes")
{
string valuestr = value.ToString();
Cube_database.DBMSTypes dbtype =
(Cube_database.DBMSTypes)Enum.Parse(typeof(Cube_database.DBMSTypes),
valuestr);
propertyInfo.SetValue(this, dbtype, null);
}
else if (propertyInfo.PropertyType.Name == "String")
{
propertyInfo.SetValue(this, value.ToString(), null);
}
else if (propertyInfo.PropertyType.Name == "Boolean")
{
propertyInfo.SetValue(this, Convert.ToBoolean(value), null);
}
else if (propertyInfo.PropertyType.Name == "Int32")
{
propertyInfo.SetValue(this, Convert.ToInt32(value), null);
}
}
catch (Exception exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
}


Dans le code ci-dessus, RegistryAccess.GetValue renvoie un object lue
dans une valeur de la base registre.




Ce qui m'étonne dans votre code c'est le fait que vous ayez un problème
qui n'est pas du niveau du code...

Copier-coller ?
Avatar
J-L
> Ce qui m'étonne dans votre code c'est le fait que vous ayez un problème qui
n'est pas du niveau du code...

Copier-coller ?




C'est un pur copier-coller. Il manque seulement la fonction inverse
RegistryToProperty que voilà:

private void PropertyToRegistry(ParameterAttribute parameterAttribute,
PropertyInfo propertyInfo)
{

string keyname = pathreg + parameterAttribute.Category;

if (propertyInfo != null)
{
switch (parameterAttribute.RegistryKey)
{
case RegistryKeys.rkUser:
RegistryAccess.SetValue(KeyType.HKEY_CURRENT_USER,
keyname, parameterAttribute.Name, propertyInfo.GetValue(this, null));
break;
case RegistryKeys.rkLocalMachine:
RegistryAccess.SetValue(KeyType.HKEY_LOCAL_MACHINE,
keyname, parameterAttribute.Name, propertyInfo.GetValue(this, null));
break;
default:
break;
}
}
}


et le code de RegistryAccess :

public static void SetValue(KeyType keyType, string keyName, string
valueName, object value)
{
RegistryKey registrykey = Key(keyType, keyName);
if (registrykey != null)
{
registrykey.SetValue(valueName, value);
registrykey.Close();
}
}

public static object GetValue(KeyType keyType, string keyName, string
valueName)
{
object obj = null;
RegistryKey registrykey = Key(keyType, keyName);
if (registrykey != null)
{
obj = registrykey.GetValue(@valueName);
registrykey.Close();
}
return obj;
}

private static RegistryKey Key(KeyType keyType, string keyName)
{

// Insure that key and value exist
CreateKey(keyType, keyName);

RegistryKey registrykey;
switch (keyType)
{
case KeyType.HKEY_CLASSES_ROOT:
registrykey =
Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(keyName, true);
break;
case KeyType.HKEY_CURRENT_USER:
registrykey =
Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyName, true);
break;
case KeyType.HKEY_LOCAL_MACHINE:
registrykey =
Microsoft.Win32.Registry.LocalMachine.OpenSubKey(keyName, true);
break;
case KeyType.HKEY_USERS:
registrykey =
Microsoft.Win32.Registry.Users.OpenSubKey(keyName, true);
break;
case KeyType.HKEY_CURRENT_CONFIG:
registrykey =
Microsoft.Win32.Registry.CurrentConfig.OpenSubKey(keyName, true);
break;
default:
registrykey = null;
break;
}

return registrykey;

}