Чтобы ограничить то, что вы запускаете как sudo, вы можете запустить
python non_sudo_stuff.py
sudo -E python -c "import os; os.system('sudo echo 1')"
без необходимости хранить пароль. Параметр -E
передает env вашего текущего пользователя процессу. Обратите внимание, что ваша оболочка будет иметь привилегии sudo после второй команды, поэтому используйте ее с осторожностью!
Вызов GetType ()
для типа значения блокирует этот тип значения. Переместив тип значения в кучу, вы получите ссылочный тип, который теперь имеет указатель на тип этого объекта.
Если вы хотите избежать упаковки, вы можете вызвать GetTypeCode
, который возвращает перечисление, которое указывает тип типа значения без его упаковки.
Вот пример, показывающий происходящую упаковку:
C #:
class Program
{
static void Main()
{
34.GetType();
}
}
IL для Main ()
:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: ldc.i4.s 0x22
L_0002: box int32
L_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
L_000c: pop
L_000d: ret
}
Изменить: Чтобы показать, что делает компилятор, давайте изменим тип литерала следующим образом:
class Program
{
static void Main()
{
34L.GetType();
}
}
Добавив "L"
после литерала, я сообщаю компилятору, что хочу, чтобы этот литерал быть преобразованным в System.Int64
.
Maybe Andrew H. took this as obvious and tried hard to make me understand +1. my light-bulb moment came from Jon Skeet.. again (this time via his book which I happened to be reading.. and around the exact region where the answers lay.
Consider the snippet below. Although the variable type is BaseRefType, it points to an object of a more specialized type. For value types, since inheritance is outlawed, the variable type is the object's type.
BaseRefType r = new DerivedRefType();
ValueType v = new ValueType();
My missing piece was bullet#1.
. There seems to be some magic that lets the compiler/runtime know the 'type of the variable' given any arbitrary variable.
So the runtime somehow knows that ob is of MyStruct type, even though the VT object itself has no type information.
MyStruct ob = new MyStruct();
ob.WhoAmI(); // no box ; defined in MyStruct
Console.WriteLine(ob.GetHashCode()); // no box ; overridden in ValueType
Console.WriteLine( ob.GetType() ); // box ; implemented in Object
Due to this, I am able to invoke methods defined in MyStruct (and ValueType for some reason) without boxing to a RefType.