Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

CSharp:Conversioni generiche

From Aino Wiki

Jump to: navigation, search

E' possibile impostare la cultura INVARIANT che abbia effetto su tutte le istruzioni sensibili alla cultura negli automatismi di conversione come ad es. Double.Parse("00.04");:

Using ...;
...
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

ha effetto nel Thread corrente!.

Tipo generico

La seguente funzione è simile alla TryParse canonica ma la si fa funzionare su un tipo generico quindi variabile esso stesso. Esempio preso da stackoverflow.

/// <summary>
/// Analoga alla "TryParse" associata ad un tipo solo che qui il tipo è generico/è una variabile esso stesso
/// </summary>
/// <typeparam name="T">Tipo in cui convertire il valore</typeparam>
/// <param name="stringValue">Stringa col valore</param>
/// <param name="convertedValue">Valore convertito nel tipo indicato</param>
/// <returns>Indica se la conversione ha funzionato</returns>
public static bool TryConvertValue<T>(string stringValue, out T convertedValue)
{
	var targetType = typeof(T);
	if (targetType == typeof(string))
	{
		convertedValue = (T)Convert.ChangeType(stringValue, typeof(T));
		return true;
	}
	var nullableType = targetType.IsGenericType &&
				   targetType.GetGenericTypeDefinition() == typeof(Nullable<>);
	if (nullableType)
	{
		if (string.IsNullOrEmpty(stringValue))
		{
			convertedValue = default(T);
			return true;
		}
		targetType = new NullableConverter(targetType).UnderlyingType;
	}
 
	Type[] argTypes = { typeof(string), targetType.MakeByRefType() };
	var tryParseMethodInfo = targetType.GetMethod("TryParse", argTypes);
	if (tryParseMethodInfo == null)
	{
		convertedValue = default(T);
		return false;
	}
 
	object[] args = { stringValue, null };
	var successfulParse = (bool)tryParseMethodInfo.Invoke(null, args);
	if (!successfulParse)
	{
		convertedValue = default(T);
		return false;
	}
 
	convertedValue = (T)args[1];
	return true;
}

Esempio d'uso

Si usa il metodo 'TryConvertValue()' indicato sopra per un caso reale:

private static bool UpdateModel_Generic<T>(IInputStream inputStream,
											NeptuneDataCollector.Plugin.Interfaces.IDecoder decoderInstance,
											string sampleName,
											DraftInfoSubscrChanged draftInfo)
{
	bool ok = true;
	string strTypeOf = string.Empty;
	try
	{
		System.Type targetType = typeof(T);
		strTypeOf = targetType.ToString();
 
		T genericTypeValue;
 
		if (Helper.TryConvertValue<T>(draftInfo.Value, out genericTypeValue))
		{
			SampleHeader sh = new SampleHeader()
			{
				SampleName = sampleName,
				CompanyCode = NeptuneDataCollector.Data.Utils.CompanyCodeByConfig,
				ShipCode = NeptuneDataCollector.Data.Utils.ShipCodeByConfig,
				Timestamp = draftInfo.SourceTimestampUTC,
				Reliability = 1 // !!!!! x ora è così !!!!!
			};
 
			decoderInstance.DoWork(inputStream, genericTypeValue, sh);
			ok = true;
			m_ModelLastUpdateDateUTC = DateTime.UtcNow;
			m_logger.Debug("'{0}' (EntityName: {1}) value '{2}' correctly dispatched.",
						sampleName, draftInfo.EntityName, draftInfo.Value);
		}
		else
		{
			ok = false;
			m_logger.Error("Failure converting '{0}' (EntityName: {1}) '{2}' to '{3}'.", 
							sampleName, draftInfo.EntityName, draftInfo.Value ?? "NULL", strTypeOf);
		}
	}
	catch (Exception ex)
	{
		ok = false;
		m_logger.Error("Ex: {0}\r\n{1}", ex.Message, ex.StackTrace);
	}
	return ok;
}

Numeriche

Da double ad int
int result = 0;
double value = 0;
//..
value = MathFunction(x, y);
//..
result = Convert.ToInt32(value);

Stringhe o Char

GuId

Da stringa in GuID:

Guid gID = new Guid(txtPositionId.Text); // Dove txtPositionId.Text ha la stringa es: sdf5-43fgf-45gg ...

Date

Date vs String

Conversione da una data DateTime in stringa formattata con ToString(":
string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
string text2 = dateTime.ToString("dd/MM/yyyy HH:mm:ss.fff");

Conversione da una stringa formattata con ToString(" in DateTime, usando l'invariant culture (InvariantCulture):
DateTime myDate = DateTime.ParseExact("2014-12-15 14:40:55,532", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);
Al posto di "2014-12-15 14:40:55,532" si può sostituire con la stringa contenente il valore variabile.
Tabella di conversione con formato
Specifier	DateTimeFormatInfo property	Pattern value (for en-US culture)
t	ShortTimePattern	h:mm tt
d	ShortDatePattern	M/d/yyyy
T	LongTimePattern	h:mm:ss tt
D	LongDatePattern	dddd, MMMM dd, yyyy
f	(combination of D and t)	dddd, MMMM dd, yyyy h:mm tt
F	FullDateTimePattern	dddd, MMMM dd, yyyy h:mm:ss tt
g	(combination of d and t)	M/d/yyyy h:mm tt
G	(combination of d and T)	M/d/yyyy h:mm:ss tt
m, M	MonthDayPattern	MMMM dd
y, Y	YearMonthPattern	MMMM, yyyy
r, R	RFC1123Pattern	ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s	SortableDateTi­mePattern	yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u	UniversalSorta­bleDateTimePat­tern	yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
 	 	(*) = culture independent

Esempi di codice:

String.Format("{0:t}", dt);  // "4:06 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2009"                        ShortDate
String.Format("{0:T}", dt);  // "4:06:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2009"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2009 4:06 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2009 4:06:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2009 4:06 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2009 4:06:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2009"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2009-03-09T17:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2009-03-09 17:05:07Z"            UniversalSortableDateTime

String vs DateTimeOffset

/* ES. di VALORE CORRETTO per un offset = 2 è
				  strDateTimeOffsetValue = '2015-06-16T12:59:04.0000000+02:00'      */
DateTimeOffset dto = DateTimeOffset.ParseExact(strDateTimeOffsetValue, "o", System.Globalization.CultureInfo.InvariantCulture);

String vs DateTime

Nel caso la data nella stringa sia in formato Italiano ovvero il primo Agosto 2017

string date = "01/08/2017";
IFormatProvider culture = new System.Globalization.CultureInfo("it-IT", true);
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);

Nel caso la data nella stringa sia in formato Statunitense ovvero l'8 Gennaio 2017

string date = "01/08/2017";
IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);

String vs Date

Quando si deve usare un campo Date (senza l'orario) per una query sul DB (SQL Server) da C# non c'è un modo funzionate di eseguire la conversione. DateTime.Date non può esser convertito in SQL. Conviene usare il metodo EntityFunctions.TruncateTime . Aggiungere la reference alla DLL System.Data.Entity (e la 'using System.Data.Objects;').

using System.Data.Objects;
 
var eventsCustom = eventCustomRepository
.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);

Char Array

Usando ToCharArray:
string input = "Hello World!";
char[] values = input.ToCharArray();

Esadecimale

Da una stringa ottengo una stringa con il valore esadecimale di ciascun carattere (es. preso da Microsoft MSDN):
string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
Esempio

Byte

byte b = Convert.ToByte('<');
//ovvero: 60 == 0x3c

Da stringa esadecimale a stringa di bit

Data una stringa di n caratteri ciascuno un valore esadecimale ecco come convertire ciascuno di questi in stringa di 4 bit e concatenare:

using System;
using System.Linq;
 
public class Program
{
	public static void Main()
	{
		string hexstring = "12345678";
 
		string binarystring = String.Join(String.Empty,
		  hexstring.Select(
			c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')
		  )
		);
 
		Console.WriteLine("binarystring: {0}", binarystring);
		// Output: 00000001001000110100010101100111
	}
}

Dat DataTable a List<T>

Mappa e Link


C# | Conversioni


Visual Studio | Tips programmazione libreria


Parole chiave:String.Format, String.Format(", Linq, select, Padding, Pad, Convert

Author